4

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 Answer 1

6

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!

Sign up to request clarification or add additional context in comments.

2 Comments

yeah apparently i was just missing that else :)
Just to piggyback- OP, maximum recursion depth is almost always a telltale sign of an infinite loop. A common error that leads to infinite loops is incorrect base cases, as we have seen here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.