我有一個關於在Python中使用遞歸的概念懷疑。 以下是用於僅使用遞歸的反轉堆棧的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'不是全局的,它被傳入函數。 –