Implementing Stack with Python

前端 未结 12 1258
长发绾君心
长发绾君心 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 17:00

    The proper implementation would include __iter__ also since Stack needs to be LIFO order.

    class Stack:
        def __init__(self):
            self._a = []
    
        def push(self, item):
            self._a.append(item)
    
        def pop(self):
            return self._a.pop()
    
        def isEmpty(self):
            return len(self._a) == 0
    
        def __iter__(self):
            return reversed(self._a)
    
        def __str__(self):
            # return str(list(reversed(self._a)))
            return str(list(iter(self)))
    
    def main():
        stack = Stack()
        stack.push('a')
        stack.push('b')
        stack.push('c')
        stack.pop()
        print(stack)
        if stack:
            print("stack not empty")
        stack.pop()
        stack.pop()
        if stack.isEmpty():
            print("stack empty")
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题