Reputation: 442
I'm very new to python (just started yesterday), and I'm trying to create permutations of a character set e.g. ascii_lowercase for use in a crypto program. I'm currently using the following:
...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
given a character set of 'abc' it will give:
a
b
c
aa
ab
ac
bb
...etc
It managed to correctly hit 'aa'; however, it missed 'ba' and for a cryptographic hashing algorithm ab != ba. Essentially I would like to find an itertools.permutations_with_replacement function.
Is there any way to get both ba and bb?
Upvotes: 2
Views: 519
Reputation: 63737
Its seems you need itertools.product rather than itertools.combinations_with_replacement
And here is the implementation with 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
Note if you need to use the value rather than to print it you can always use the generator
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
Upvotes: 2