Search code examples
python-3.xloopsnested-loops

Add an iteration variable in a nested for-loop on every iteration


I'm trying to write a program that prints every possible alphabetical combination between two and four characters. The program as I have it now works just fine, but the implementation is far from ideal. This is what it is now:

# make a list that contains ascii characters A to z
ascii = list(range(65, 123))
del ascii[91 - 65 : 97 - 65] # values 91-97 aren't letters

for c1, c2 in product(ascii, repeat=2):
    word = chr(c1) + chr(c2)
    print(word)

for c1, c2, c3 in product(ascii, repeat=3):
    word = chr(c1) + chr(c2) + chr(c3)
    print(word)

for c1, c2, c3, c4 in product(ascii, repeat=4):
    word = chr(c1) + chr(c2) + chr(c3) + chr(c4)
    print(word)

I'd much rather have something in the spirit of the following. Forgive me that the following code is totally wrong, I'm trying to convey the spirit of what I thought would be a nicer implementation.

iterationvars = [c1, c2, c3, c4]

for i in range(2,5):
    for iterationvars[0:i] in product(ascii, repeat=i):
        word = ??
        print(word)

So I have two questions:
1) how can I change the number of iteration variables of a nested for loop on every iteration of the 'mother loop'?
2) how can word be implemented such that it dynamically adds up all iteration variables, no matter how many there are on that particular iteration.

Of course, very different implementations from what I suggest are also more than welcome. Thanks a lot!


Solution

  • there's no need to change the number of iteration variables, just keep it all in one tuple then use a joined list comprehension. Something like this would work:

    for iter_tuple in product(ascii, repeat = i):
        word = ''.join(chr(x) for x in iter_tuple)
        print(word)