Neil
Neil

Reputation: 147

How to fix "maximum recursion depth exceeded" error in python code?

While I was running the code, I got a "maximum recursion depth exceeded in comparison" error. I'm not exactly sure which part of the code to look at to fix this problem. This numToBinary function is basically supposed to convert a number n to a binary number with bit size k. I would greatly appreciate any input on how I can resolve this issue!

def numToBinary(k, n):
''' converts number to binary number bit size k'''
def binary(n):
    if n == 0:
        return ''
    elif n%2 == 1:
        return  binary(n/2)+'1' 
    else:
        return binary(n/2)+ '0'
temp = binary(n)
if len(temp) <= k:
    answer = '0' * (k - len(temp)) + temp
elif len(temp) > k:
    answer = temp[-k:]
return answer


print (numToBinary(6, 10))

Upvotes: 1

Views: 462

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180522

You need floor division, double /, in python3 / does truediv so you are getting floats from n/2:

  def binary(n):
        if n == 0:
            return ''
        elif n%2 == 1:
            return  binary(n//2) + '1' # // floor
        else:
            return binary(n//2)+ '0' # // floor

Once you make the change, it will work fine:

In [50]: numToBinary(6, 10)
Out[50]: '001010'

You can also use else in place of the elif, if the len of temp is not <= then it has to be greater than:

def numToBinary(k, n):
    ''' converts number to binary number bit size k'''
    def binary(n):
        if n == 0:
            return ''
        elif n % 2 == 1:
            return  binary(n//2)+'1'
        else:
            return binary(n//2) + '0'
    temp = binary(n)
    if len(temp) <= k:
        answer = '0' * (k - len(temp)) + temp
    else:
        answer = temp[-k:]
    return answer

If you wanted to see exactly what was happening you should put a print in you own code, if you added a print(n) in binary you would see a lot of output like:

5.125332723668738e-143
2.562666361834369e-143
1.2813331809171846e-143
6.406665904585923e-144
3.2033329522929615e-144

Which meant you eventually hit the recursion limit.

Upvotes: 1

Related Questions