Implementing Stack with Python

前端 未结 12 1272
长发绾君心
长发绾君心 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:45

    class Stack:
       s =[]
    
       def push(self, num):
           self.s.append(num)
    
       def pop(self):
           if len(self.s) == 0: # erro if you pop an empty list
               return -1
           self.s.remove(self.s[-1])
    
       def isEmpty(self):
           if len(self.s) == 0:
               return True
           else:
               return False
    
       def display(self): # this is to display how a stack actually looks like
           if self.isEmpty():
               print("Stack is Empty")
        
           for i in range(len(self.s)-1,-1,-1): # I haven't used reversed() since it will be obv
               print(self.s[i])
    
    
    obj = Stack()
    obj.push(3)
    print(obj.isEmpty())
    obj.push(4)
    obj.display()
    print("----")
    obj.pop()
    obj.display()
    

提交回复
热议问题