使用 while 或 if 作为递归条件会导致不同的结果

Using while or if as a condition for recursion leads to different results

这是一个简单的递归函数,应该运行10次,条件是if。

count = 0  
def recurse(count):
    *if* count < 10:
        print count
        count += 1
        recurse(count)

recurse(count)

输出

0 1 2 3 4 5 6 7 8 9 好的

当我使用 while 循环时,结果大不相同,我不明白为什么它不输出 0 到 9。

代码

count = 0
def recurse(count):
    *while* count < 10:
        print count
        count += 1
        recurse(count)

recurse(count)

输出

0 1 2 3 4 5 6 7 8 9 9 8 9 9 7 8 9 9 8 9 9 6 7 8 9 9 8 9 9 7..... 8 9 9

你可以在这里试试 https://repl.it/nHa/3,不过我不知道如何用代码创建 link。

任何人都看到我做错了什么。

编辑。

代码 2 的输出是有限的。

示例使用 3 作为限制。

您正在迭代 and 递归,就好像您使用了 for 而不是 if 在第一个例子中。

人们经常在迭代和递归之间做出选择。在 while 循环情况下,您试图同时执行这两项操作。 If 是测试终止递归条件的正确选择。

问题是 count 对于您正在调用的每个函数都是本地的!因此,每次调用 recursive 函数时,您都会再次 iterate 循环!因此,您的 base-case 永远不会满足。使用 return ,您将获得所需的输出。这是因为您随后将保存变量 count 的状态。 (另一种方法是使 count 成为一个全局变量,这是一种糟糕的方法)

count = 0
def recurse(count):
    while count < 10:
        print count
        count += 1
        count = recurse(count)
    return count

recurse(count)

在这里,您在外部递归函数中将计数值重新分配回您的变量,因此您的基本情况将得到满足。

你做错了什么取决于你想要达到什么...但是无论你想要什么,我都不相信 代码

def recurse(count):
    if count < 10:
        print count
        count += 1
        recurse(count)

给你输出

0..9

您需要在 if 块中return递归:

count = 0
def recurse(count):
    if count < 10:
        print(count)
        return recurse(count+1)

In [63]: recurse(0)
0
1
2
3
4
5
6
7
8
9

并在 while 块中执行相同的操作:

def recurse(count):
    while count < 10:
        print(count)
        count += 1
        return recurse(count)

显示递归调用和顺序的图表可能会有所帮助:

我们从 0 开始,然后递归到 1、2,最后是 3,然后我们移动到 2,再次递归到 3,最后我们到达最后一个数字 3,函数结束。

现在当你 return:

时会发生什么

颜色和编号的含义:

Note: 1. The edges are numbered by the order in which they were traversed by the execution. 2. The edges are colored from black to grey to indicate order of traversal: black edges first, grey edges last.

图表是使用 rcviz

生成的

您调用 recurse(0),从 0 到 9。它 调用 recurse(1)recurse(2)、...、recurse(10)。每个依次打印数字并引起更多 recurse(...) 调用,每个再次打印数字并引起更多调用。等等。这当然爆炸了。