Home > Net >  Why does the code keep recursing even though a condition for while is set?
Why does the code keep recursing even though a condition for while is set?

Time:09-28

The following code is supposed to transform the binary into decimal. However, even though there is a while condition intended to stop it from going forever it still gives me the error RecursionError: maximum recursion depth exceeded while calling a Python object

def binary_into_decimal(useful_number, length_of_string):
    working_length = 0
    list_useful_number = list(useful_number)
    power = int(length_of_string - working_length)
    will_be_summed = []
    current_number = int(list_useful_number[working_length])
    calculation = current_number * (2 ** power)
    while working_length < (length_of_string   1):
        will_be_summed.append(calculation)
        working_length  = 1
        binary_into_decimal(useful_number, length_of_string)
        print("hey")

CodePudding user response:

It is an infinite loop because you are re-initializing the value of working_length back to 0 every time you call binary_into_decimal(useful_number, length_of_string) in while loop. So it actually never overcome the condition of the while loop.

In while loop every time you execute binary_into_decimal(useful_number, length_of_string) . First line of your function (working_length = 0) gets executed.

CodePudding user response:

Although recursion is a dumb way to do this, here's how you can change a binary string to decimal recursively:

def binary_into_decimal( bits, sofar = 0 ):
    if not bits:
        return sofar
    sofar *= 2
    if bits[0] == '1':
        sofar  = 1
    return binary_into_decimal( bits[1:], sofar )

print( binary_into_decimal( '1100' ) )
print( binary_into_decimal( '10101' ) )

Here's a different way that doesn't carry the accumulator as a parameter:

def binary_into_decimal( bits ):
    if not bits:
        return 0
    return int(bits[-1])   2 * binary_into_decimal( bits[:-1] )

print( binary_into_decimal( '1100' ) )
print( binary_into_decimal( '10101' ) )
  • Related