Joseph Arsany
Joseph Arsany

Reputation: 11

How to deal with nested loops when you don't know how many loops need nesting (python 3.4)?

The question is framed a bit weird but to give an example, i am trying to write a program that lists all the possible alphanumerical strings given the length of the string.

so far my code is:

from itertools import product

alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

charnum = input('How many characters\n>>>')

for a,b,c,d,e,f,g,h in product(alpha, repeat = charnum):
    print(a+b+c+d+e+f+g+h)

it is currently build assuming that the length is 8 characters however if i don't know the number i can't chose the variable names that go after the keyword 'for'.

Upvotes: 1

Views: 464

Answers (1)

gyre
gyre

Reputation: 16777

You can use ''.join and a single looping variable seq, like so:

from itertools import product

alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

charnum = int(input('How many characters\n>>>'))

for seq in product(alpha, repeat = charnum):
    print(''.join(seq))

Upvotes: 3

Related Questions