python - 如何查找输入字符串中常见字符的数量
问题描述
我想接受输入并执行操作以查找输入(字符串)中常见字母的数量。
示例输入:
abcaa
bcbd
bgc
输出为 2,因为 b 和 c 都存在。
我尝试编写代码,但我被困在第 4 行:
t = int(input())
for i in range(3):
s1=input()
#a=list(set(s1)&set(s2))
print(a)
'''
input:
3
abcaa
bcbd
bgc
output:
2
because 'b' and 'c' are present in all three
'''
解决方案
输入要比较的数量:
as_many_inputs = 3
asked_inputs = [set(input("Enter the string you want\t")) for i in range(as_many_inputs)]
from functools import reduce
print("Number of common is:\t", len(reduce(set.intersection, asked_inputs)))
在这里,您可以使用内置的 reduce() 函数来查找交集。此外, len() 将返回数字。
Enter the string you want aah
Enter the string you want aak
Enter the string you want aal
Number of common is: 1
我也用 5 做了测试:
Enter the string you want agh
Enter the string you want agf
Enter the string you want age
Enter the string you want agt
Enter the string you want agm
Number of common is: 2