'How can I skip a piece of code in recursion?
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 the function, when I call recursion?
arr = []
for i in inp:
arr.append(i)
Solution 1:[1]
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
Solution 2:[2]
if whatever: ... is possible in recursion as well and can skip things inside your function - but there is no need:
You do not need to add an implicit carry (result=0) to your function signature if you do recursion the right way:
def bin_to_decimal(inp, degree=0):
if len(inp) == 1: # base case
return 2**degree*int(inp[0])
# "12345" => "1234" into remainder and "5" into x by decomposition
*remainder, x = inp # decompose
# calc the value of x and recurse with remainder and 1 degree higher
return 2**degree*int(x)+bin_to_decimal(remainder, degree+1)
for n in range(17):
b = bin(n)[2:] # this function converts int to bin with a 0b prefix
print(b, bin_to_decimal(b), sep=" ==> ")
Output:
0 ==> 0
1 ==> 1
10 ==> 2
11 ==> 3
100 ==> 4
101 ==> 5
110 ==> 6
111 ==> 7
1000 ==> 8
1001 ==> 9
1010 ==> 10
1011 ==> 11
1100 ==> 12
1101 ==> 13
1110 ==> 14
1111 ==> 15
10000 ==> 16
Recursion is not needed here, you can unroll it:
def bin_to_decimal(inp):
num = 0
degree = 0
for digit in inp[::-1]: # reversed
num += int(digit) * 2**degree
degree += 1
return num
or simpy use num = int("0100101", 2) to convert it.
Solution 3:[3]
If you want a "closest to your code as possible" solution, you can use:
def bin_to_decimal(inp, degree=0, result=0):
arr = list(inp) # this does what your loop does ... just shorter
# list("abc") => ["a","b","c"]
# list(["a","b","c"]) => ["a","b","c"] where it is not needed
if not arr:
return result
else:
x = arr.pop(-1)
result += int(x)**degree
# use arr here, not inp
return bin_to_decimal(arr, degree+1, result)
but using a carry like you do is bad style regarding recursion.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Freddy Mcloughlan |
| Solution 2 | |
| Solution 3 | Patrick Artner |
