【问题标题】:Can someone help explain this python recursive code?有人可以帮助解释这个python递归代码吗?
【发布时间】:2018-07-23 00:46:34
【问题描述】:

我正在尝试使用递归对堆栈进行排序,以使最小的元素位于堆栈的顶部。当我运行代码时,结果有时是不可预测的。

这里是代码

class stack:
def __init__(self):
    self.items = []
def push(self, item):
    self.items.append(item)
def pop(self):
    return self.items.pop()
def peek(self):
    return self.items[len(self.items)-1]
def is_empty(self):
    return self.items == []
def size(self):
    return len(self.items)

class sort_the_stack:

    def __init__(self):
        self.sorted_stack = stack()

    def sort_stack(self, new_stack):
        for i in range(new_stack.size()):
            self.push(new_stack.pop())
        return self.sorted_stack

    def push(self, val):
        if self.sorted_stack.size() == 0:
            self.sorted_stack.push(val)
        else:
            temp = self.sorted_stack.peek()
            if val < temp:
                self.sorted_stack.push(val)
            else:
                temp = self.sorted_stack.pop()
                self.push(temp)
                self.sorted_stack.push(temp)

    def peek(self):
        return self.sorted_stack.peek()

    def pop(self):
        return self.sorted_stack.pop()

new_stack = stack()

new_stack.push(10)

new_stack.push(2)

new_stack.push(1)

new_stack.push(8)

new_stack.push(10)

new_stack.push(10)

stack1 = sort_the_stack()

stack1.sort_stack(new_stack)


print(stack1.pop())

print(stack1.pop())

print(stack1.pop())

print(stack1.pop())

print(stack1.pop())

print(stack1.pop())

【问题讨论】:

  • 堆栈已经用 Python 实现了,为什么要自己实现?
  • @MichaelRobellard:通常是因为这是家庭作业:(
  • @TapasBalu:您能否展示一下您方面的尝试以找到解决此问题的方法?
  • 你的递归调用在哪里?也许我只是忽略了它,但没有看到一个..
  • 我正在做一些堆栈练习,并试图不使用已经实现的堆栈

标签: python sorting recursion stack


【解决方案1】:

在您的递归情况下,您似乎将 temp 值推送了两次,而不是您实际尝试添加的值。你有

else:
 temp = self.sorted_stack.pop()
 self.push(temp)
 self.sorted_stack.push(temp)

但我认为你想要

else:
 temp = self.sorted_stack.pop()
 self.push(val)
 self.sorted_stack.push(temp)

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多