0

如果我有一个可变单词中的单词列表和可变字母中的字母列表,我怎样才能找到可以由字母中的字母组成的所有单词。可以使用变量 letters 中的任何字母子集,并且可以多次使用字母。我想在 Python 中做到这一点。

例如:

letters = ['a', 'b', 'i', 'l', 'r', 's', 't', 'u']
words = ['dummy', 'australia']

应该返回:

'australia'

即使有一个额外的'b',但不是:

'dummy'

因为 d、m 和 y 不可用。

4

4 回答 4

3

使用正则表达式:

>>> import re
>>> m = re.compile('^[abilrstu]+$')
>>> m.match('australia') is not None
True
>>> m.match('dummy') is not None
False
>>> m.match('australian') is not None
False
于 2013-02-02T10:46:22.487 回答
0

您可以all()与 一起使用sets,因为它们允许O(1)会员检查:

In [9]: words = ['dummy', 'australia']

In [10]: letters = ['a', 'b', 'i', 'l', 'r', 's', 't', 'u']

In [11]: let_set=set(letters)

In [12]: for word in words:
    if all(x in let_set for x in set(word)):
        print word
   ....:         
australia
于 2013-02-02T10:44:39.330 回答
0

这可能是最简单的方法:

result = [w for w in words if all(i in letters for i in w)]

这返回['australia']

于 2013-02-02T10:45:02.477 回答
0

这采用了设置交集,这可能会更快。另一方面,它需要额外的内存。

letters = ['a', 'b', 'i', 'l', 'r', 's', 't', 'u']
words = ['dummy', 'australia', 'australians' ]

f = set(letters)
c = [ (word, set(word)) for word in words ]
# changing to s & f == f makes condition "must use ALL letters"
s = [ w for (w, s) in c if s & f == s ]

s 现在['australia']

(但我很好奇这种解决方案的使用。一个拼字游戏机器人?对字典密码的灰尘键盘攻击?)

于 2013-02-02T11:12:08.223 回答