Now, let's write Python code to generate all the passwords of length n.
def gen_nested_loop(n):
res = "def gen_passwords():\n"
for i in range(n):
res += "%sfor letter%d in alphabet:\n" % ((1+i)*" ", i)
add_line = "password = "
for i in range(n-1):
add_line += "letter%d + " % (i)
add_line += "letter%d" % (n-1)
res += (n+1)*" " + add_line + "\n"
res += (n+1)*" " + "print(password)\n"
return res
Here's the string that gen_nested_loop(5) returns:
gen_nested_loop(5)
Let's print it:
print(gen_nested_loop(5))
We can now save the string, and then run it with exec. We'll then be able to call the function gen_passwords().
alphabet = "abc"
program_text = gen_nested_loop(2)
print(program_text)
exec(program_text)
gen_passwords()