Skip to main content
 首页 » 编程设计

python之带数学运算符的递归函数

2025年05月04日87zlslch

我想构建一个函数,它接受两个自然数 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)