多个堆栈代码不会增加堆栈号

时间:2018-08-10 04:15:13

标签: python collections stack defaultdict

这是我本人在Python中实现的SetOfStacks问题(CTCI 3.3)。简而言之,我想将堆栈的大小限制为10。因此,当我尝试增加容量时,我又生成了一个堆栈,以使用户继续推送新元素。我试图将其表示为 collections.defaultdict(list)数据结构。为了跟踪使用中的堆栈号,我创建了一个名为 current_stack 的变量。但是,即使在容量过剩的情况下(请参阅#####标记处的设计),看来current_stack不会按预期增加 。我的代码有什么问题? self.current_stack不能在对象内充当全局变量吗?

class SetOfStacks():
    def __init__(self, stacksize):
        self.size = stacksize  # const
        self.c = collections.defaultdict(list)
        self.current_stack = 0  # self.c[self.current_stack]

    def push(self, e):
        if len(c[self.current_stack]) + 1 > self.size: #####
            self.current_stack += 1
        self.c[self.current_stack].append(e)

    def pop(self):
        if self.current_stack > 0 and len(c[self.current_stack]) == 1 :
            popped = self.c[self.current_stack].pop()
            self.current_stack -= 1
            return popped
        elif self.current_stack == 0 and len(c[self.current_stack]) == 0:
            raise IndexError("No more elements to pop.")
        else:
            return self.c[self.current_stack].pop()

    def __repr__(self):
        return print(self.c)

st = SetOfStacks(10)
for i in range(21):
    st.push(i)
st

结果:

defaultdict(<class 'list'>, {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]})

1 个答案:

答案 0 :(得分:1)

您在Baz的{​​{1}}通话中缺少self

len()

您需要:

push()

在您引用的环境中,您必须有另一个def push(self, e): if len(c[self.current_stack]) + 1 > self.size: ##### ^ 且从未添加到其中-大小始终不变。

def push(self, e): if len(self.c[self.current_stack]) + 1 > self.size: ##### 中也有一些类似的错误,例如:

c

注意:pop()应该返回def pop(self): if self.current_stack > 0 and len(c[self.current_stack]) == 1 : ^ 而不是实际的def __repr__():,例如:

str

使用这些修复程序,您将获得预期的输出:

print()
相关问题