def recursion(x):
if x == 0:
return 0
else:
return x << 1 + recursion(x - 1)
print(recursion(3)) # 393216
print(3 << 1) # 6
print(2 << 1) # 4
print(1 << 1) # 2
In my head the output of the recursion function should be: 12 (6+4+2) Why is this not the case? I must say "393216" is slightly bigger than my expected number "12".
My expectation:
--> return 1<<1==2 for 1
--> return 2<<1==4 for 2
--> return 3<<1==6 for 3
0 --> return 0 for 0
All together = 12
The reason is due to operator precedence. Bitshift operators have lower precedence than arithmetic.
By default, x << 1 + recursion(x - 1)
is assumed to be x << (1 + recursion(x - 1))
.
You can fix the issue by overriding the default precedence using parentheses.
def recursion(x):
if x == 0:
return 0
else:
return (x << 1) + recursion(x - 1)
print(recursion(3)) # 12
Operator precedence. Bit shifts have lower precedence than addition/subtraction (see in docs). Hence you need
def recursion(x):
if x == 0:
return 0
else:
return (x << 1) + recursion(x - 1)
as currently your function is being interpreted equivalent to
def recursion(x):
if x == 0:
return 0
else:
return x << (1 + recursion(x - 1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With