我们可以从中间分开一个长字符串,并检查两个半部分是否相等。输入的字符串可以包含奇数或偶数个字符。如果它的字符数是偶数,我们将两半除以一半的长度。但是,如果字符数为奇数,则我们忽略最中间的字符,然后比较剩余的两半。
在下面的程序中,我们使用上述逻辑创建输入字符串的两半,然后
from collections import Counter def comparehalves(input_string): str_len = len(input_string) # If number of characyes is odd # ignore the middle character if (str_len % 2 != 0): left = input_string[0:int(str_len / 2)] right = input_string[(int(str_len / 2)) + 1:] else: left = input_string[0:int(str_len / 2)] right = input_string[int(str_len / 2):] # Convert the halves into lists # and sort them l1 = list(left) l1.sort() l2 = list(right) l2.sort() if l1 == l2: print ("Same character in both halves") else: print ("Both halves are different ") in_string = input("Enter String: ") comparehalves(in_string)
输出结果
运行上面的代码给我们以下结果-
# Run1 Enter String: Tutorials Both halves are different # Run2 Enter String: TutTut Same character in both halves