def bin_to_decimal(inp, degree=0, result=0):
arr = []
for i in inp:
arr.append(i)
if not arr:
return result
else:
x = arr.pop(-1)
result += int(x)**degree
return bin_to_decimal(inp, degree+1, result)
bin_to_decimal('1001')
Is it possible to skip this part of function, when I call recursion?
arr = []
for i in inp:
arr.append(i)
>Solution :
You can use:
def bin_to_decimal(inp, degree=0, result=0, skip=False):
if skip:
arr = []
for i in inp:
arr.append(i)
if not arr:
return result
else:
x = arr.pop(-1)
result += int(x)**degree
# Flag True to skip
return bin_to_decimal(inp, degree+1, result, True)
But you will now have an unreferenced variable arr
- along with a few more errors
I suggest you have a look at some other methods that you can use:
Built-in:
>>> int('1001',2)
9
Iteration:
def bin_to_decimal(inp):
x = 0
for i in inp:
x = x*2 + int(i)
return x