Skip to main content
 首页 » 编程设计

python之Python 中的递归和元组

2025年05月04日90over140

<分区>

我正在尝试编写两个接受整数并返回元组的函数。我可以非常接近想要返回的内容,但我返回的内容中有多个括号。例如,我希望 rec_range(5) 返回 (0,1,2,3,4) 而不是 (((((0, 1), 2), 3), 4)。

这是我写的两个函数

def rec_range(n): 
    '''Takes a natural number n and returns a tuple of numbers starting 
       with 0 and ending before n. 
       Int-->Tuple''' 
 
    if n == 0: 
         return  
    if n == 1: 
        return 0 
    if n >= 1: 
        return rec_range(n-1),(n-1) 
 
def squares_tuple(n,m): 
    '''Takes a natural numbers n and m and returns a tuple of the squares 
       of all the natural numbers starting with n and ending with m-1. 
       Int,Int-->Tuple''' 
 
    while n<=m: 
        return n * n, squares_tuple(n + 1, m)