例如
String = "The boy who cried wolf made many many silly mistakes."
def f(n):
。
f(3)
应输出:
4
因为只有2个字母,“a”,“m”,“y”和“e”出现三次以上。
到目前为止,我已经尝试过以及到目前为止的目标:
String = "The boy who cried wolf made many many silly mistakes."
a={}
def f(n):
for s in String:
if s in a:
a[s] +=1
else:
a[s] = 1
我不确定下一步该做什么
答案 0 :(得分:3)
您可以使用集合模块中的Counter Class。
>>> from collections import Counter
>>> string = "The boy who cried wolf made many many silly mistakes."
>>> Counter(string)
Counter({' ': 9, 'e': 4, 'a': 4, 'y': 4, 'm': 4, 's': 3, 'i': 3, 'o': 3, 'l': 3, 'n': 2, 'd': 2, 'h': 2, 'w': 2, 'T': 1, 'b': 1, '.': 1, 'k': 1, 'r': 1, 't': 1, 'c': 1, 'f': 1})
>>> m = 0
>>> c = Counter(string)
>>> for i in c:
if i.isalpha() and c[i] > 3:
m += 1
>>> m
4
将其定义为单独的功能。
from collections import Counter
def f(n):
c = Counter(n)
m = 0
for i in c:
if i.isalpha() and c[i] > 3:
m += 1
return m
stri = "The boy who cried wolf made many many silly mistakes."
print f(stri)
答案 1 :(得分:3)
from collections import Counter
s = "The boy who cried wolf made many many silly mistakes."
sum(1 for k, v in Counter(s).items() if v > 3 and k.isalpha())
<强>输出强>
4
或者您可以定义一个函数。
def f(s, n):
return sum(1 for k, v in Counter(s).items() if v > n and k.isalpha())
和
f(s, 3) #return 4
答案 2 :(得分:1)
使用collections.Counter
肯定是一种很好的方法;但是,如果您不想导入任何内容,请考虑以下内容。
string = "The boy who cried wolf made many many silly mistakes."
def f(n):
alpha_chars = filter(lambda char: char.isalpha(), string)
greater_chars = 0
for char in list(set(alpha_chars)):
if string.count(char) > n:
greater_chars += 1
return greater_chars
f(3)
将输出4
。
但是,as explained here,最好使用字符串作为参数。
my_string = "The boy who cried wolf made many many silly mistakes."
def f(string, n):
...
然后,您可以使用f(my_string, 3)
进行调用,这将输出4
。