python - 两个字符串中的常用字母

标签 python string

我一直在尝试解决这个程序,该程序将两个字符串作为输入并输出常用字母的数量。例如,如果输入是“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/

相关文章:

用于处理转义分隔符和转义转义字符的 Java String.split() 正则表达式

python - 基于索引列表返回子列表的最简单和最有效的函数是什么?

php - 在 php 中制作 H2-H3 元素列表

Python:带有对象列表的对象——根据列表成员的属性创建方法

python - 高效地生成 16 个字符的字母数字字符串

c++ - 用字符串中的空格替换符号

c - C中的char string [LENGTH]和char * string [LEN]有什么区别

c++ - 不使用正则表达式解析 HTTP 请求

python - 如何使用Python选择x级深的JSON数据

python - 递归计算 DataFrame 值