【发布时间】:2018-12-03 21:16:28
【问题描述】:
def print_numbers(n, k):
"""Print all numbers that (A) can be formed from the digits of `n` in reverse
order and (B) are multiples of `k`.
Args: n (int): The number that results must use digits from.
k (int): The number that results must be multiples of.
>>> print_numbers(97531, 5)
135
15
35"""
def inner(n,s):
if n == 0:
if s % k == 0 and s > 0:
print(s)
else:
inner(n // 10, s*10 + n % 10) #first
inner(n // 10, s) #second
inner(n,0)
我在理解递归调用的部分时遇到了一些麻烦。据我了解,在第一次到达应该给出返回值的阶段之前,不能调用第二次递归调用。但是,第一个调用的作用(在示例中): 它给出了inner(9753,1),inner(975,13),inner(97,135),inner(9,1357),inner(0,13579)
当 n 等于 0 时,s(13579) 不能被 k(5) 整除,因此它不打印任何内容。此外,通过构造函数的方式返回值是None。因此,当达到 inner(0,13579) 阶段时,第二个递归调用必须开始工作,但它会不断尝试 0 // 10 并且不会继续。
这是我的理解。你能指出我错在哪里吗?
【问题讨论】:
标签: python recursion higher-order-functions