我尝试制作此代码并运行它,但结果显示"无"。 我通过在循环函数中添加另一个else进行编辑,然后它实际上产生了' 57'这不是答案。
def double(n):
return n*2
def halve(n):
return n//2
def mult(m,n):
def loop(m,n):
if n>1:
if n%2 != 0:
return m + loop(double(m),halve(n))
else:
return m #added another else
else:
return m
if n>0:
return loop(m,n)
else:
return 0
print(mult(57,86))
答案 0 :(得分:1)
通过简单的递归
def double(n):
return n * 2
def halve(n):
return n // 2
def mult(m, n, a = 0):
if n % 2 != 0:
a = a + m
m = double(m)
n = halve(n)
if n % 2 == 0:
m = double(m)
n = halve(n)
if n != 0:
return mult(m, n, a)
return a
print(mult(57, 86))
通过嵌套函数
def double(n):
return n * 2
def halve(n):
return n // 2
def mult(m, n):
def loop(m, n, a = 0):
if n % 2 != 0:
a = a + m
m = double(m)
n = halve(n)
if n % 2 == 0:
m = double(m)
n = halve(n)
if n != 0:
return loop(m, n, a)
return a
return loop(m, n)
print(mult(57, 86))