【发布时间】:2019-05-13 15:13:15
【问题描述】:
我对在 python 中使用递归有一个概念上的疑问。 下面是我从this page at geeksforgeeks复制的仅使用递归来反转堆栈的python代码。
# Below is a recursive function that inserts an element
# at the bottom of a stack.
def insertAtBottom(stack, item):
if isEmpty(stack):
push(stack, item)
else:
temp = pop(stack)
insertAtBottom(stack, item)
push(stack, temp)
# Below is the function that reverses the given stack
# using insertAtBottom()
def reverse(stack):
if not isEmpty(stack):
temp = pop(stack)
reverse(stack)
insertAtBottom(stack, temp)
似乎函数reverse 使用stack 作为全局变量,因为被调用函数没有向调用函数返回任何新值。这不是实现递归的错误方式吗?我们不应该避免在堆栈中使用全局变量吗?
另外,我们如何编辑这个函数,使得被调用函数的每个实例都使用它自己的stack 副本?
【问题讨论】:
-
请尝试将您的句子分解为“我希望...函数”。这很头疼..
-
stack不是全局的,它被传递到函数中。