-->

Iterate a to zzz in python

2020-03-24 02:31发布

问题:

So I need to get a function that generates a list of letters that increase from a, and end in zzz.

Should look like this:

a
b
c
...
aa
ab
ac
...
zzx
zzy
zzz

The code I currently have is this:

for combo in product(ascii_lowercase, repeat=3):
            print(''.join(combo))

However, this does only increase with 3 letters, and the output is more like

a
ab
abc
abcd
...

So, to recap: Function that letters increase, and when it goes past z, it returns to aa. Thanks!


UPDATE:

I am having the same output as before. Here is what I am trying to plug it into:

a = hashlib.md5()
for chars in chain(ALC, product(ALC, repeat=1), product(ALC, repeat=1)):
    a.update(chars.encode('utf-8'))
    print(''.join(chars))
    print(a.hexdigest())

My hash ends up like:

f1784031a03a8f5b11ead16ab90cc18e

but I expect:

415290769594460e2e485922904f345d

Thanks!

回答1:

from string import ascii_lowercase as ALC
from itertools import chain, product

for chars in chain(ALC, product(ALC, repeat=2), product(ALC, repeat=3)):
    print(''.join(chars))

RESPONDING TO THE QUESTION UPDATE

I tried all the methods, but couldn't get 415290769594460e2e485922904f345d what you mentioned you expect.. so I don't know how you calculated your expectation.

product                       : 1a431d62ddd9e78e1b22f8245ad945d0
permutations                  : 52d2529adf73975a4ca82bc7e25db4c6
combinations                  : 52bf3fcd925b2fdc1c52df70b7e33cbb
combinations_with_replacement : 421d5ff16fc211ae253fcc3e81eeb262


回答2:

Add another loop:

for x in range(1, 4):
    for combo in product(ascii_lowercase, repeat=x):
        print(''.join(combo))

Output is as follows:

a
...
aa
...
aaa
...
zzz

Where ... is a huge number of combinations.