RecursionError: maximum recursion depth exceeded in comparison Python

Viewed 1923

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?

1 Answers

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!

Related