Implementing Stack with Python

前端 未结 12 1093
长发绾君心
长发绾君心 2021-01-17 16:16

I am trying to implement a simple stack with Python using arrays. I was wondering if someone could let me know what\'s wrong with my code.

class myStack:
            


        
12条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 16:48

    Assigning to self won't turn your object into a list (and if it did, the object wouldn't have all your stack methods any more). Assigning to self just changes a local variable. Instead, set an attribute:

    def __init__(self):
        self.stack = []
    

    and use the attribute instead of just a bare self:

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

    Also, if you want a stack, you want pop() rather than pop(0). pop(0) would turn your data structure into a(n inefficient) queue.

提交回复
热议问题