用于检查字符串的两半是否具有相同字符集的Python程序。
给定一个字符串,我们的任务是检查字符串的两半是否具有相同的字符集。为了解决这个问题,我们首先从中间拆分字符串,这样我们得到了两半,现在我们检查每个半角是否具有相同的字符集。如果字符串的长度不是偶数,则忽略中间元素并检查其余部分。
算法
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.
范例程式码
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)输出结果
Enter The String abba Both halves are same
热门推荐
9 敏字的祝福语简短
10 新年恋人祝福语简短创意
11 韩语贺卡祝福语简短版
12 孙媳妇祝福语简短
13 员工对同事祝福语简短
14 档案调动孩子祝福语简短
15 生日祝福语舅舅 简短独特
16 老婆生日祝福语简短孩子
17 妈妈生日贺卡祝福语 简短
18 送水杯祝福语女生简短