Search code examples
pythonloopsfor-loopnested-loops

Replace Nested For Loops... or not


I have a script that loops through a series of four (or less) characters strings. For example:

aaaa
aaab
aaac
aaad

If have been able to implement it with nested for loops like so:

chars = string.digits + string.uppercase + string.lowercase

for a in chars:
    print '%s' % a   
    for b in chars:
        print '%s%s' % (a, b)
        for c in chars:
            print '%s%s%s' % (a, b, c)
            for d in chars:
                print '%s%s%s%s' % (a, b, c, d)

Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?


Solution

  • import string
    import itertools
    
    chars = string.digits + string.letters
    MAX_CHARS = 4
    for nletters in range(MAX_CHARS):
        for word in itertools.product(chars, repeat=nletters + 1):
            print (''.join(word))
    

    That'll print all 15018570 words you're looking for. If you want more/less words just change the MAX_CHARS variable. It will still have just two fors for any number of chars, and you don't have to repeat yourself. And is pretty readable. .