Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để kiểm tra xem cả hai nửa của chuỗi có cùng một bộ ký tự hay không.

Cho một chuỗi, nhiệm vụ của chúng ta là kiểm tra xem cả hai nửa của chuỗi có cùng một bộ ký tự hay không. Để giải quyết vấn đề này, trước tiên chúng ta tách chuỗi từ giữa, vì vậy chúng ta sẽ có hai nửa, bây giờ chúng ta kiểm tra mỗi nửa có cùng một bộ ký tự hay không. Nếu độ dài của chuỗi không bằng nhau thì hãy bỏ qua phần tử ở giữa và kiểm tra phần còn lại.

Thuật toán

Step 1: Given a string.
Step 2: Break the input string into two parts.
Step 3: Then convert both parts into a dictionary using Counter(iterator) method and each dictionary contains its character as key and frequency as value.
Step 4: Now compare these two dictionaries. Here we use == operator. First we checks keys of both dictionaries are same or not,
then checks for values of each key. If both cases are true then two halves have the same set of characters.

Mã mẫu

from collections import Counter
def checkhalves(input):
   length = len(input)
   if (length % 2 != 0):
      first = input[0:int(length / 2)]
      second = input[(int(length / 2)) + 1:]
   else:
      first = input[0:int(length / 2)]
      second = input[int(length / 2):]
   if Counter(first) == Counter(second):
      print ("Both halves are same")
   else:
      print ("Both halves are not same ")
# Driver program
if __name__ == "__main__":
input = input("Enter The String")
checkhalves(input)

Đầu ra

Enter The String abba
Both halves are same