【问题标题】:Generating words upto and including 20 letters生成最多包含 20 个字母的单词
【发布时间】:2017-12-10 22:37:49
【问题描述】:
alphabet =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
key = ''
for a in range(26):
    key += alphabet[a]
    print(key)
    key = ''

for a in range(26):
    for b in range(26):
        key += alphabet[a]+ alphabet[b]
        print(key)
        key = ''

for a in range(26):
    for b in range(26):
        for c in range(26):
            key += alphabet[a]+ alphabet[b]+ alphabet[c]
            print(key)
            key = ''

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

【问题讨论】:

  • 你需要 itertools.permutations/combinations.
  • 不能假装我听说过,所以谢谢
  • 如果您不打算使用 itertools,请使用递归。

标签: python auto-generate


【解决方案1】:

这是不可能的。可能性的数量太多了。如果可以轻松生成最多 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

【讨论】:

  • 这需要很长时间,但我的程序有效,所以我相信你会发现它是可能的。
  • @BenWhitehead 那么您不会生成包含 20 个字符的每个可能的单词。你看上面需要的时间了吗?如果你的程序是正确的,你能指出哪里错了吗?
【解决方案2】:

下面使用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 个字母组合是绝对要求,否则您应该寻找一种方法来避免它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    相关资源
    最近更新 更多