gpt4 book ai didi

python - 用 Python 实现堆栈

转载 作者:太空狗 更新时间:2023-10-29 20:38:49 25 4
gpt4 key购买 nike

我正在尝试使用数组通过 Python 实现一个简单的堆栈。我想知道是否有人可以让我知道我的代码有什么问题。

class myStack:
def __init__(self):
self = []

def isEmpty(self):
return self == []

def push(self, item):
self.append(item)

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

def size(self):
return len(self)

s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print s

最佳答案

我纠正了下面的几个问题。此外,在抽象编程术语中,“堆栈”通常是一个集合,您可以在其中从顶部添加和删除,但是您实现它的方式是添加到顶部并从底部删除,这使它成为一个队列.

class myStack:
def __init__(self):
self.container = [] # You don't want to assign [] to self - when you do that, you're just assigning to a new local variable called `self`. You want your stack to *have* a list, not *be* a list.

def isEmpty(self):
return self.size() == 0 # While there's nothing wrong with self.container == [], there is a builtin function for that purpose, so we may as well use it. And while we're at it, it's often nice to use your own internal functions, so behavior is more consistent.

def push(self, item):
self.container.append(item) # appending to the *container*, not the instance itself.

def pop(self):
return self.container.pop() # pop from the container, this was fixed from the old version which was wrong

def peek(self):
if self.isEmpty():
raise Exception("Stack empty!")
return self.container[-1] # View element at top of the stack

def size(self):
return len(self.container) # length of the container

def show(self):
return self.container # display the entire stack as list


s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print(s.show())

关于python - 用 Python 实现堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18279775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com