Skip to main content
 首页 » 编程设计

python之反转递归产生的整数的顺序

2025年04月02日9Leo_wl

我有一个基本的递归函数,它基本上会在给定一个输入数字的情况下打印出一行数字。

def formula1(distance): 
    if distance == 1: 
        print(int(distance)) 
        return 
    elif (distance % 2) == 0: 
        print(int(distance), end=" ") 
        return formula1(distance / 2) 
    elif (distance % 2) == 1: 
        print(int(distance), end=" ") 
        return formula1(3*distance + 1) 

我现在必须反向打印数字,而不是字符串或列表。我真的不确定该怎么做,声明一个新的临时变量只会被覆盖。我认为在参数中定义变量无济于事......

在上面的函数中,显然 print() 行必须被删除,但我不确定用什么替换它,而不是试图向后计算整个计算。

例子, 公式 1 (5) 打印出 5 16 8 4 2 1 我需要它来打印 1 2 4 8 16 5

请您参考如下方法:

您只需要确保在调用 print 之前进行递归调用:

def formula1(distance): 
    if distance == 1: 
        print(distance, end=" ") 
        return 
    elif (distance % 2) == 0: 
        v = formula1(distance // 2) 
        print(distance, end=" ") 
        return v 
    else: 
        v = formula1(3 * distance + 1) 
        print(distance, end=" ") 
        return v 

对 formula1 的每次调用都有自己的本地范围,因此对 v 的赋值是不同的,并在递归调用返回后保留。