Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iteration via expandable nested 'for' loops without itertools

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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',
 ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading