计算text1中的字符在text2中出现的次数
写一个名为 occurrences 的函数,这个函数需要接收两个字符串作为参数。这个函数的作用是返回第一个字符串中的字符在第二个字符串中出现的次数。
举个例子:
occurrences('fooled', 'hello world')
这个调用应该返回:
7 (1个'e', 3个'l', 2个'o', 1个'd')
我的代码在这里:
def occurrences(text1, text2):
"""Return the number of times characters from text1 occur in text2
occurrences(string, string) -> int
"""
# add your code here
ss=0
for c in set(text2):
if c in text1:
return text1.count(text2)
return ss
它提示说: 你的循环应该遍历 text2 错误:对于字符串 'tc1h' 和 'Return the number of times characters from text1 occur in text2',你得到了0。正确的答案是15。
2 个回答
0
def occurrences(text1, text2):
"""Return the number of times characters from text1 occur in text2
occurrences(string, string) -> int
"""
text1_dict = {char:0 for char in text1}
for char in text2:
if char in text1_dict:
text1_dict[char] += 1
return sum(list(text1_dict.values()))
我写了一段代码,可以在 O(n) 的时间内解决这个问题,而不是 O(n^3)。这段代码首先创建了一个字典,里面存储了 text1 中每个字符出现的次数。接着,它会统计 text2 中的字符,并更新这个字典。最后,它返回字典中所有值的总和(不过不幸的是,字典的值不能直接求和,所以我之前用了一个列表来处理)。
1
可以用一行代码来完成:
>>> from collections import Counter
>>> sum(Counter(c for c in 'hello world' if c in 'fooled').values())
7