如何在任意顺序下创建字符集的所有排列 - Python

2 投票
1 回答
502 浏览
提问于 2025-04-17 09:18

我刚开始学习Python(昨天才开始),现在想创建一个字符集的排列,比如说ascii小写字母,用在一个加密程序里。我现在用的是以下代码:

...function definitions etc
while i <= num:
  for k in itertools.combinations_with_replacement(charset, i):
    nhash = str(''.join(k))
    fp.write(nhash + '\n')
    ...hashing code and other file I/O
  i += 1

比如说给定字符集为'abc',它会生成:

a
b
c
aa
ab
ac
bb
...etc

它成功生成了'aa',但是漏掉了'ba',在加密哈希算法中,ab和ba是不同的。所以我想找到一个类似于itertools.permutations_with_replacement的函数。

有没有办法同时得到'ba'和'bb'呢?

1 个回答

2

看起来你需要用到 itertools.product,而不是 itertools.combinations_with_replacement

下面是使用 itertools.product 的实现方式:

charset='ABC'
print '\n'.join(''.join(p) for i in xrange(1,len(charset)+1) 
                for p in itertools.product(charset, repeat=i))

A
B
C
AA
AB
AC
BA
BB
BC
CA

如果你需要使用这个值而不是仅仅打印出来,你可以使用生成器。

for x in (''.join(p) for i in xrange(1,len(charset)+1) 
                for p in itertools.product(charset, repeat=i)):
    print x
    ...hashing code and other file I/O

撰写回答