I'm trying to write a recursive function to print some sort of permutations in python. However I get maximum depth error for some reason.
def perm(chars, k, word):
if k == 0:
print(word)
for char in chars:
perm(chars, k - 1, char + word)
perm(['1','2'], 2, '')
Anyone has any idea what the error is?
You're missing a base case, causing your call stack to overflow. Add a base case by making the for loop (the recursive case) conditional:
def perm(chars, k, word):
if k == 0:
print(word)
else:
for char in chars:
perm(chars, k - 1, char + word)
perm(['1','2'], 2, '')
Output:
11
21
12
22
Try it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With