【发布时间】:2021-10-17 03:34:08
【问题描述】:
我无法完全理解以下递归函数中 return 语句的行为。在if 和else 语句中都有返回值,我得到了根据需要返回的int 值,但是删除任何一个函数都会返回None。
我预计只需要在 else 中使用 return 语句,因为通过 if 语句运行的任何迭代都会递归地启动计算函数,直到它绕过 if
def solution(n, b):
results = {}
j = 0
k = len(str(n))
return calculate(n, b, j, k, results)
def calculate(n, b, j, k, results):
i = ''
x = ''.join(sorted([i for i in str(n)])[::-1])
y = x[::-1]
z = int(x, b) - int(y, b)
while z:
i = int(str(z % b) + str(i))
z = z // b
i = '0'*(k-len(str(i))) + str(i)
if i not in results.values():
results[j] = i
j += 1
s = calculate(i, b, j, k, results)
return s #commenting this line causes code to return None
else: #commenting else statement causes code to return None
return len(results.keys()) - list(results.keys())[list(results.values()).index(i)]
print(solution('210022', 3))
【问题讨论】:
-
除了注释掉
else语句,你需要减少它的返回缩进
标签: python python-3.x recursion return