I'm having a problem making my counter work in my recursion, instead of printing 11, it prints 11,1s. where am I making a mistake?
def power(x, n):
global countcalls # note countcalls variable is in my global and it is equal to 0
countcalls = 1
print(countcalls)
if n <= 0:
return 1
else:
return x * power(x, n-1)
my output:
1
1
1
1
1
1
1
1
1
1
1
1024
output wanted :
11
1024
CodePudding user response:
First, countcalls = 1
doesn't increment the variable, it just sets it to 1
. To increment, use = 1
, not = 1
.
Second, if you only want to print at the end, put the print()
call in the base case.
Instead of using a global variable, use another parameter that defaults to 0
.
def power(x, n, countcalls = 0):
countcalls = 1
if n <= 0:
print(countcalls)
return 1
else:
return x * power(x, n-1, countcalls)