使用for循环统计两个字符串中出现的次数

-1 投票
2 回答
1035 浏览
提问于 2025-04-17 20:35

我需要帮助写一个函数,这个函数可以计算两个字符串参数中字符出现的次数。这个函数会返回第一个字符串中的字符在第二个字符串中出现的次数。

举个例子:调用 occurances('fooled','hello world') 应该返回 7(1 个 'e',3 个 'l',2 个 'o',1 个 'd')

需要使用一个 'for 循环'。


谢谢大家的帮助,非常感谢!

2 个回答

0

只需要使用一个叫做 defaultdict 的工具,来统计第一个列表中每个元素在第二个列表中出现的次数。然后把所有的次数加起来就可以了:

from collections import defaultdict

ele_count = defaultdict(int)
def occurances(first, second):
  count = 0
  for ele in second:
    if ele in first:
      ele_count[ele] += 1

  for item in ele_count.values():
    count += item

  print count
2

这里有一种使用列表推导的方法:

In [738]: def occurances(fst, sec):
     ...:     return sum(sec.count(c) for c in set(fst))

In [739]: occurances('fooled','hello world')
Out[739]: 7

你也可以把它改成一个循环:

def occurances(fst, sec):
    osum=0
    for c in set(fst):
        #try it yourself :)
    return osum

或者像@SvenMarnach和@JayanthKoushik提到的,如果不使用 set 的话:

In [738]: def occurances(fst, sec):
     ...:     return sum(c in fst for c in sec)

这种方法的运行时间是 O(mn),其中 m 和 n 分别是 fstsec 的长度。如果把 fst 变成一个 set,那么运行时间可以优化到 O(m+n):

In [738]: def occurances(fst, sec):
     ...:     fst=set(fst)
     ...:     return sum(c in fst for c in sec)  #checking "in set" is O(1) 

撰写回答