英语标题翻译成中文:使用Python生成Enigma插线板设置的最有效方法

2024-05-20 10:10:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究用python破解enigma密码,并需要生成插件板组合—我需要的是一个函数,它接受length参数并以列表的形式返回所有可能组合的生成器对象。你知道吗

示例代码:

for comb in func(2):
   print(comb)
# Example output
['AB', 'CD']
['CD', 'EF']
...

有没有人知道图书馆提供了这样一个生成器,或者如何着手制作一个生成器?你知道吗

编辑:更多关于谜的细节

有关插件板设计的详细信息,请参见here

此外,在不运行整个发电机的情况下,发电机的输出格式必须与此格式一致:

'AB FO ZP GI HY KS JW MQ XE ...'对的数目将是函数中的length参数。你知道吗


Tags: 对象函数插件密码示例列表参数ab
2条回答

我想你要找的是itertools.combinations

>>> from itertools import combinations
>>> list(combinations('abcd', 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(comb) for comb in combinations('abcd', 2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

这和你想要的很接近吗?让我知道,我可以修改。你知道吗

plugboard()函数返回(yield)一个generator对象,可以通过iterable循环或调用next()函数来访问该对象。你知道吗

from itertools import product

def plugboard(chars, length):
    for comb in product(chars, repeat=length):
        yield ''.join(comb)

这样的调用将创建combs作为generator对象:

combs = plugboard('abcde', 2)
type(combs)

>>> generator

要访问这些值,您可以使用以下任一选项:

next(combs)
>>> 'aa'

或:

for i in combs: print(i)

ab
ac
ad
ae
ba
bb
bc
...

相关问题 更多 >