检查字母是否可用于构建单词

时间:2014-09-16 15:25:05

标签: python dictionary

我有一个这样的词典:{'a': 3, 'e': 1, 'p': 2, 'r': 1, 'u': 1, 't': 1} 这意味着一个人有3次'a',有一次是'e'等。

我必须检查字母是否可用于构建单词,如下所示:

for letter in dict:
    for count in range(0,dict.get(letter)):
       if not (letter in word):
          return False

但是,这里存在问题。对于包含多个字母的单词,对于单词中的字母,它将始终返回true,因为它不会检查 2,3,4 etc 字母。

如果dict只有'z',我该如何传递zazzing这个单词的代码:1?

2 个答案:

答案 0 :(得分:3)

我会使用collections中的Counter

>>> c = Counter('zazzing')
>>> d = {'a':1,'i':2,'g':3,'n':1,'z':1,'e':3}
>>> c
Counter({'z': 3, 'a': 1, 'i': 1, 'g': 1, 'n': 1})
>>> for i in c.items():
...   if d[i[0]]<i[1]:
...      print "problem with ",i[0]
...
problem with  z

并且带有'ok'字样:

>>> c = Counter('aigeginee')
>>> for i in c.items():
...   if d[i[0]]<i[1]:
...      print "problem with ",i[0]
...

因此,您可以在for循环结束时printreturn False代替return True


您也可以简单地使用substract Counter方法(在Python≥3.2中)或-操作:

>>> Counter('zazzing') - Counter(d)
Counter({'z': 2})
>>> Counter('aigeginee') - Counter(d)
Counter()

答案 1 :(得分:2)

>>> from collections import Counter
>>> available_letters = Counter({'a':1,'i':2,'g':3,'n':1,'z':1,'e':3})
>>> for word in ('zazzing', 'grunt', 'zig', 'egg'):
...     if Counter(word) - available_letters:
...          print word, 'cannot be made with the letters'
...     else:
...          print word, 'can be made with the letters'
...
zazzing cannot be made with the letters
grunt cannot be made with the letters
zig can be made with the letters
egg can be made with the letters