Home > Net >  Iteration via expandable nested 'for' loops without itertools
Iteration via expandable nested 'for' loops without itertools

Time:10-14

I am trying to make a list of iterations of the alphabet with itself to the n-th power but I am unable to find an appropriate way of achieving this. I would rather not use itertools for the time being.

My idea is as follows, although I lack the ingenuity to turn it into code that would yield, for instance, ['A', 'B', ..., 'Z'] for n = 0, ['AA', 'AB', ..., 'ZZ'] for n = 1, and so on, where n is the power of the self-iteration:

import string

a = list(string.ascii_uppercase)

aa = []
for i in a:
    for j in a:
        for k in a:
            for l in a:
                ... (n-4 times)
                   aa.append(i   j   k   l   ...)

Desired output: ['AAAAAAA', 'AAAAAAB', ..., 'ZZZZZZZ']

I am self-taught, so I may not have come up with the simplest of workarounds or solutions - keep this in mind. I appreciate your inputs in advance. Have a good day.

CodePudding user response:

Using recursivity can do the trick in a very concise manner in your case:

import string
alphabet = string.ascii_uppercase

def f(n):
    if n == 0:
        return [""]
    else:
        return [x   y for x in f(n-1) for y in alphabet ] 

A call to f(n) concatenates all letters to all returned values in f(n-1) and return this new list. If n == 0 you return a list of an empty string.

Output:

f(3)

gives

['AAA',
 'AAB',
 'AAC',
 'AAD',
 'AAE',
 'AAF',
 'AAG',
 'AAH',
 'AAI',
 'AAJ',
 'AAK',
 'AAL',
 'AAM',
 ...
  • Related