创建一个不能有重复值的堆栈

时间:2019-10-15 15:09:35

标签: python stack

我刚刚接触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. """

我对堆栈有更多的选择,但是如果有人对如何启动此基础有任何想法/提示,我会考虑的!

1 个答案:

答案 0 :(得分:1)

这是一种使用set来跟踪堆栈中已经存在哪些元素的方法。要点:

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