【发布时间】:2017-12-26 21:37:04
【问题描述】:
知道为什么我的 Stack 合并排序不起作用吗?它与我的数组合并排序非常相似,但它可以工作。我的递归设置错了吗?
谢谢!
def sort(stack):
if len(stack) > 1:
middle = len(stack) // 2
stack_len = len(stack)
left = Stack()
right = Stack()
for i in range(middle):
left.push(stack.pop())
for i in range(middle, stack_len):
right.push(stack.pop())
sort(left)
sort(right)
while(not left.is_empty() and not right.is_empty()):
if (left.top() < right.top()):
stack.push(right.pop())
else:
stack.push(left.pop())
while(not left.is_empty()):
stack.push(left.pop())
while(not right.is_empty()):
stack.push(right.pop())
这是我的 Stack ADT 实现:
class Stack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self) == 0
def push(self, i):
self._data.append(i)
def pop(self):
if not self.is_empty():
return self._data.pop()
raise IndexError('Cannot pop an empty Stack.')
def top(self):
if not self.is_empty():
return self._data[len(self) - 1]
raise IndexError('Cannot check the top of an empty Stack.')
我的测试用例是:
if __name__ == '__main__':
s = Stack()
s.push(8)
s.push(0)
s.push(-4)
s.push(11)
s.push(19)
s.push(21)
s.push(3)
s.push(14)
s.push(1)
s.push(14)
print(s._data)
sort(s)
print(s._data)
给出:
[8, 0, -4, 11, 19, 21, 3, 14, 1, 14]
[19, 14, 1, 21, 3, 14, -4, 8, 0, 11]
【问题讨论】:
-
它到底有什么问题?您没有显示任何输入,没有预期的输出,没有实际的输出,没有错误。只是一段代码和“为什么这不起作用?”请相应地编辑您的问题。
-
@DavidMakogon 已修复。
-
问题没有提到要使用的堆栈数量是否有限制。通常涉及合并排序和堆栈的作业或程序挑战会限制允许的堆栈数量,这需要自下而上的方法,因为自上而下的方法会分配许多堆栈。然而,目标也可能只是处理堆栈的 LIFO 特性。
标签: python sorting merge stack mergesort