我一直在尝试解决这个程序,该程序将两个字符串作为输入并输出常用字母的数量。例如,如果输入是“common”和“connor”,那么输出应该是 4(1 c、1 n 和 2 o)。我使用了 set() 函数,但它输出 3(它将两个 o 都视为一个普通的信 )。任何帮助将不胜感激。谢谢!!!
顺便说一句,这是我写的代码:
print("Enter number of inputs: ")
c = int(input())
store = []
for each_item in range(c):
print("Enter First String: ")
one = input()
print("Enter Second String")
two = input()
s = len(set(one) & set(two))
store.append(s)
for each_number in store:
print(each_number)
最佳答案
使用 collections.Counter
:
>>> from collections import Counter
>>> Counter('common')
Counter({'m': 2, 'o': 2, 'c': 1, 'n': 1})
>>> Counter('connor')
Counter({'o': 2, 'n': 2, 'c': 1, 'r': 1})
>>> common = Counter('common') & Counter('connor') # intersection
>>> common
Counter({'o': 2, 'c': 1, 'n': 1})
>>> sum(common.values())
4
关于python - 两个字符串中的常用字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21798222/