我想构建一个函数,它接受两个自然数 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 ()
Example:
>>> squares_tuple(0, 6)
(0, 1, 4, 9, 16, 25)
>>> squares_tuple(3, 7)
(9, 16, 25, 36)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)