我试图从任何给定的字符串中找出固定单词的出现数。
固定单词= 'hackerearth‘
随机字符串可以是s= 'aahkcreeatrhaaahkcreeatrha‘
现在,我们可以从字符串中生成2次黑客地球。
我编写了一些代码来查找字符串中(h,a,e,r,c,k,t)的字母数:
代码:
word = list(raw_input())
print word
h = word.count('h')
a = word.count('a')
c = word.count('c')
k = word.count('k')
e = word.count('e')
r = word.count('r')
t = word.count('t')
if (h >= 2 and a >= 2 and e >= 2 and r >=2) and (c >= 1 and k >= 1 and t >=1 ):
hc = h/2
ac = a/2
ec = e/2
rc = r/2
num_words = []
num_words.append(hc)
num_words.append(ac)
num_words.append(ec)
num_words.append(rc)
num_words.append(c)
num_words.append(k)
num_words.append(t)
print num_words
输出:
[2, 4, 2, 2, 2, 2, 2]
从上面的输出列表中,我要计算单词的总出现量。
如何获得固定单词的总数以及其他使代码更容易的方法?
发布于 2016-11-15 02:15:44
你可以利用Counter
from collections import Counter
s = 'aahkcreeatrhaaahkcreeatrha'
word = 'hackerearth'
wd = Counter(word)
sd = Counter(s)
print(min((sd.get(c, 0) // wd[c] for c in wd), default=0))
输出:
2
上面的代码将创建两个类似于dict
的计数器,其中字母是键,它们的出现是值。然后,它将使用生成器表达式迭代在单词中找到的字母,并为每个字母生成比率。min
将选择最低比率,0
的default
值用于word
为空字符串的情况。
发布于 2016-11-15 02:17:25
查找子字符串时,需要说明字符顺序,而不仅仅是计数。
像这样的事情应该有效:
def subword(lookup,whole):
if len(whole)<len(lookup):
return 0
if lookup==whole:
return 1
if lookup=='':
return 1
if lookup[0]==whole[0]:
return subword(lookup[1:],whole[1:])+subword(lookup,whole[1:])
return subword(lookup,whole[1:])
例如:
In [21]: subword('hello','hhhello')
Out[21]: 3
因为您可以选择3个h
中的每一个,并用其余的构造hello这个单词。
https://stackoverflow.com/questions/40606805
复制