生成包含20个字母的单词

时间:2017-12-10 22:37:49

标签: python auto-generate

contact_form = ContactForm(request.POST, request.FILES)

喂!我需要一个有效的程序来生成20个或更少字母的每个单词。我已经创建了上面的代码来生成所有可能的1,2和3个字母单词。但是,这似乎是一种效率低下的方法。所以我的问题是:'是否有更有效的方法来生成这些单词,包括20个字母' 编辑:如果有帮助,我在python 2.7.9中

2 个答案:

答案 0 :(得分:2)

这是不可能的。可能性的数量太高了。如果很容易生成最多20个字符的所有组合,那么密码破解将非常容易。

假设我们每秒可以生成1000万个组合,生成所有可能的20个字符组合需要多长时间?注意,这只是20个字符的单词 - 它不包括19个字符单词或6个字符单词。

>>> combinations = 20**26
>>> per_second = 10000000
>>> seconds_required = combinations / per_second
>>> combinations
6710886400000000000000000000000000
>>> int(seconds_required)
671088640000000000000000000
>>> days_required = seconds_required / 60 / 60 / 24
>>> int(days_required)
7767229629629629202432
>>> years_required = days_required / 365
>>> int(years_required)
21280081177067479040
>>> age_of_universe = 13800000000
>>> int(age_of_universe)
13800000000

您可以使用itertools.product生成特定长度的组合,但您需要计算特定长度所需的时间(以及使用的内存量)。我想你会发现,一旦你打了8到10个字母,计算就变得不合理了。

>>> from itertools import product
>>> import string
>>> l = list(product(string.ascii_lowercase, repeat=5))
>>> len(l)
11881376

答案 1 :(得分:1)

以下使用itertools.product生成字母和''.join的组合,将它们合并为一个单词。

from string import ascii_lowercase as lowercase
from itertools import product

length = 5

for word in (''.join(x) for x in product(lowercase, repeat=length)):
    print(word)

无论你做什么,这都需要很长时间。即使是一个5个字母的单词也会有26**5个可能性,可以达到11881376或近1200万。除非产生所有20个字母组合是绝对必要的,否则你应该寻找一种避免它的方法。