【问题标题】:Min/max for itertools in PythonPython中itertools的最小值/最大值
【发布时间】:2017-02-21 09:21:54
【问题描述】:

我有这个代码:

import itertools
res = itertools.product('abc', repeat=3) 
for i in res: 
    print ''.join(i)

问题是我不知道如何为要输出的单词添加最小值和最大值?所以假设我输入了字母'a''b''c',但我只想要最少 1 个字母和最多 2 个字母的单词:我该怎么做?我已经在互联网上搜索过,但找不到任何东西。它旨在为蛮力制作字典。

【问题讨论】:

  • 最少 1 个字母是什么意思?就像你不想要'aa'一样?

标签: python dictionary itertools brute-force


【解决方案1】:

使用 itertools.permutations()。然后连接结果。

S = [x for x in permutations('abc',2)] + [ x for x in permutations('abc',1)]

其实你也可以使用products。唯一的区别是产品会删除重复的结果。但是当所有元素都不同时,您将不会有任何重复。

【讨论】:

  • 考虑到上下文(为暴力攻击构建字典),允许重复是有意义的,因此使用排列会更好。
【解决方案2】:

这个呢?

import itertools
min_letters = 1
max_letters = 2
for num in range(min_letters, max_letters + 1):
    res = itertools.product('abc', repeat=num) 
    for i in res: 
        print ''.join(i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2022-01-26
    • 2016-05-19
    • 2015-07-04
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多