[英]List all possible words with n letters
I want to list all possible words with n letters where the first letter can be a1 or a2, the second can be b1, b2 or b3, the third can be c1 or c2, ... Here's a simple example input-output for n=2 with each letter having 2 alternatives: 我想列出所有具有n个字母的单词,其中第一个字母可以是a1或a2,第二个可以是b1,b2或b3,第三个可以是c1或c2,...这是n的简单输入输出示例= 2,每个字母有2个选择:
I tried doing this recursively by creating all possible words with the first 2 letters first, so something like this: 我尝试通过先创建前两个字母的所有可能单词来递归地执行此操作,如下所示:
def go(l):
if len(l) > 2:
head = go(l[0:2])
tail = l[2:]
tail.insert(0, head)
go(tail)
elif len(l) == 2:
res = []
for i in l[0]:
for j in l[1]:
res.append(i+j)
return res
elif len(l) == 1:
return l
else:
return None
However, this becomes incredibly slow for large n or many alternatives per letter. 但是,对于每个字母较大的n或许多替代项,这变得非常慢。 What would be a more efficient way to solve this?
有什么更有效的方法来解决这个问题?
Thanks 谢谢
I think you just want itertools.product
here: 我认为您只想在这里
itertools.product
:
>>> from itertools import product
>>> lst = ['ab', 'c', 'de']
>>> words = product(*lst)
>>> list(words)
[('a', 'c', 'd'), ('a', 'c', 'e'), ('b', 'c', 'd'), ('b', 'c', 'e')]`
Or, if you wanted them joined into words: 或者,如果您希望它们加入单词中:
>>> [''.join(word) for word in product(*lst)]
['acd', 'ace', 'bcd', 'bce']
Or, with your example: 或者,以您的示例为例:
>>> lst = [["a","b"],["c","d"]]
>>> [''.join(word) for word in product(*lst)]
['ac', 'ad', 'bc', 'bd']
Of course for very large n
or very large sets of letters (size m
), this will be slow. 当然,对于非常大的
n
或非常大的字母集(大小m
),这将很慢。 If you want to generate an exponentially large set of outputs ( O(m**n)
), that will take exponential time. 如果要生成一组指数较大的输出(
O(m**n)
),则将花费指数时间。 But at least it has constant rather than exponential space (it generates one product at a time, instead of a giant list of all of them), and will be faster than what you were on your way to by a decent constant factor, and it's a whole lot simpler and harder to get wrong. 但是至少它具有恒定的空间而不是指数空间(它一次生成一个产品,而不是所有产品的庞大列表),并且以相当的恒定因子比您要达到的速度更快,并且更容易出错。
You can use the permutations
from the built-in itertools module to achieve this, like so 您可以使用内置itertools模块中的
permutations
来实现此目的,就像这样
>>> from itertools import permutations
>>> [''.join(word) for word in permutations('abc', 2)]
['ab', 'ac', 'ba', 'bc', 'ca', 'cb']
test.py : test.py:
def generate_random_list(alphabet, length):
if length == 0: return []
c = [[a] for a in alphabet[:]]
if length == 1: return c
c = [[x,y] for x in alphabet for y in alphabet]
if length == 2: return c
for l in range(2, length):
c = [[x]+y for x in alphabet for y in c]
return c
if __name__ == "__main__":
for p in generate_random_list(['h','i'],2):
print p
['h', 'h']
['h', 'i']
['i', 'h']
['i', 'i']
def generate_random_list(alphabet, length):
c = []
for i in range(length):
c = [[x]+y for x in alphabet for y in c or [[]]]
return c
if __name__ == "__main__":
for p in generate_random_list(['h','i'],2):
print p
import itertools
if __name__ == "__main__":
chars = "hi"
count = 2
for item in itertools.product(chars, repeat=count):
print("".join(item))
import itertools
print([''.join(x) for x in itertools.product('hi',repeat=2)])
from itertools import product
#from string import ascii_letters, digits
#for i in product(ascii_letters + digits, repeat=2):
for i in product("hi",repeat=2):
print(''.join(i))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.