python - 创建一个不能有重复值的堆栈
问题描述
我刚接触python,但对堆栈的概念有疑问!我有一个任务要求我创建一个唯一的堆栈,其中不能有两个相同的值,但是我对如何运行堆栈来检查这一点感到困惑。
from stack import Stack
class UniqueStack(Stack):
""" UniqueStack has the same methods and functionality as Stack, but will only store one copy of a particular item at a time. If push is called with an item that is already in the UniqueStack, a ValueError should be raised with an appropriate error message. If push is called where item equals None, a TypeError should be raised like in the base class. Define and implement the relevant methods from the base Stack class to enable the behavior described above. New versions of __init__(), push(), and pop() should be sufficient. Hint: One option to implement this is to maintain an internal set() alongside the internal list. """
我有更多的变化与堆栈有关,但如果有人对如何开始这个基础有任何想法/提示,我会接受它们!
解决方案
这是一种使用 aset
来跟踪堆栈中已经存在哪些元素的方法。要点:
1)添加元素时,检查集合。并添加到堆栈并设置两者。
2)删除元素时,请确保也从集合中删除。
class UniqueStack(object):
def __init__(self):
self._seen = set()
self._stack = list()
def push(self, val):
if val in self._seen:
raise ValueError('Already in stack')
self._stack.append(val)
self._seen.add(val)
def pop(self):
if not self._stack:
raise ValueError('stack is empty')
retval = self._stack.pop(-1)
self._seen.remove(retval)
return retval
def __str__(self):
return '/'.join(map(str, self._stack))
if __name__ == '__main__':
stack = UniqueStack()
for i in range(5):
stack.push(i)
print(stack)
try:
stack.push(4) # Error
except:
print("Got error")
pass
print(stack.pop())
stack.push(4)
print(stack)
输出:
0/1/2/3/4
Got error
4
0/1/2/3/4
推荐阅读
- javascript - 在鼠标光标悬停时播放选定的视频/光标关闭时暂停
- oracle - 循环遍历数组以获取 where 条件 pl/sql
- php - 在codeigniter中上传图片Rest api
- android - 在特定设备上使用 Let's Encrypt 的 ERR_SSL_PROTOCOL_ERROR
- java - 无法使用 Groovy/Grails Tool Suite 在 grails 项目中打开文件
- stata - 使用制表符时删除列
- android - 如何在 OnDestroy 中关闭运行时权限对话框?
- laravel - Lumen 在执行 phpunit 时不会迁移包表
- css - 如何将第三方样式标记为@media screen {}
- facebook - 创建 Facebook 广告帐户沙盒帐户并解锁 ads_read -(AKA:从 facebook 开始阅读入门教程)