我想构建一个函数,它接受两个自然数 n 和 m,并返回以 n 开头并以 m-1 结尾的所有自然数的平方元组。如果 m 小于 n,我可以决定函数是否应该返回,但它不应该崩溃或返回某种错误消息。所以 squares_tuple(3,7) 返回 (9,16,25,36) 而 rec_range(10,11) 返回 (100,)。另外,我不想使用 range()、map()、循环或列表。这是我目前所拥有的:
def squares_tuple(n,m):
"""takes two nat nums n and m and returns a tuple of the squares of all the
natural numbers starting with n and ending with m-1
nat, nat -> tuple of natural numbers"""
if m >= 0:
return 0
else:
return squares_tuple(n - 1, ) + (n**m, )
此时有点卡住...
最佳答案
def squares_tuple(n, m):
return (n * n, ) + squares_tuple(n + 1, m) if n < m else ()
例子:
>>> squares_tuple(0, 6)
(0, 1, 4, 9, 16, 25)
>>> squares_tuple(3, 7)
(9, 16, 25, 36)
关于python - 带数学运算符的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265845/