Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecursionError: maximum recursion depth exceeded in comparison Python

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?

like image 1000
user4464936 Avatar asked Nov 14 '25 10:11

user4464936


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!

like image 61
ggorlen Avatar answered Nov 17 '25 06:11

ggorlen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!