我一直在尝试解决这个程序,该程序将两个字符串作为输入并输出常用字母数。例如,如果输入是“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)
答案 0 :(得分:8)
>>> 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
答案 1 :(得分:0)
你也可以列出理解
>>> a = 'common'
>>> b = 'connor'
>>> sum([1 for l in a if l in b])
4
修改强>
a,b = 'come','common'
def collision_count(a,b):
da = {l:a.count(l) for l in a}
db = {l:b.count(l) for l in b}
return sum(min(v,db[k]) for k,v in da.items() if k in db.keys())
print collision_count(a,b)
3
你现在好吗?