python - 我无法理解 python 中的对象操作
问题描述
我尝试使用下面的代码使用 2 个堆栈来实现队列。
实用程序堆栈实现。
class Stack():
def __init__(self,array = []):
self.array = array
def is_empty(self):
return self.array == []
def pop(self):
if self.array == []:
raise Exception('stack is empty')
else:
popped_element = self.array.pop()
return popped_element
def push(self,key):
self.array.append(key)
def top(self):
return self.array[-1]
def __repr__(self):
return " ".join(list(map(str,self.array)))
if __name__ == "__main__":
q = Stack()
q.push(1)
q.push(2)
q.push(3)
q.push(4)
q.push(5)
print(q.pop())
print(q.pop())
print(q.pop())
q.push(10)
print(q)
from stack import Stack
class TwoStackQueue1():
def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def enqueue(self,key):
self.stack1.push(key)
def dequeue(self):
while(self.stack1.is_empty() != True):
top = self.stack1.top()
print("eval_dequeue",top)
self.stack2.push(top)
self.stack1.pop()
if self.stack2.is_empty() == True:
raise Exception("Queue is empty")
else:
top = self.stack2.pop()
return top
def is_empty():
return self.stack1.is_empty() and self.stack2.is_empty()
if __name__ == "__main__":
q = TwoStackQueue1()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
print(q.stack1)
print(q.dequeue())
当我尝试对队列执行上述操作时,我的代码陷入无限递归,因为我的堆栈的弹出操作不起作用。有人可以帮我弄清楚为什么我的代码(队列操作:- q.dequeue())陷入无限递归吗?谢谢。
解决方案
问题在于,由于您使用了可变的默认参数这一事实,您有效地使对象的内部状态成为单例。
换句话说,由于默认情况下您可以用来初始化 Stack 的数组是空列表,因此任何未来的实例都将不仅使用空列表,而且将使用与所有先前的 Stack 实例相同的列表。
试试这个快速修复:
class Stack():
def __init__(self,array=None):
self.array = array or []
...
推荐阅读
- python - 如何在 python 中使用自定义编码来伪代码?
- node.js - 显示最后删除消息的“狙击”命令
- javascript - vue-router 不渲染子组件
- objective-c - "because it is not SIP-protected" - Apple event error in macOS Mojave
- sql - 查询计数有多少记录在日期范围之外
- php - PHP Elasticsearch 在字符串开头搜索
- javascript - ngx-datatable 高亮列
- java - 如何在测验应用程序中为 Firebase 数据创建随机数?
- python - 在 opencv 窗口中显示实时流和自定义图像
- swift - UITableView 单元格延迟扩展