开发者

Stack data structure in python

I have 2 issues with the code below:

  1. push(o) throws an exception TypeError: can only assign an iterable.
  2. Should I throw an exception if pop() is invoked on an empty stack ?

    class Stack(object):
    
        def __init__(self):
            self.storage = []
    
        def isEmpty(self):
            return len(self.storage) == 0
    
        def push(self,p):
            self.storage[:0] = p
    
        def pop(self):
            """issue: throw exception?"""
            return None开发者_如何转开发
    


No need to jump through these loops, See 5.1.1 Using Lists as Stacks

If you insist on having methods isEmpty() and push() you can do:

class stack(list):
    def push(self, item):
        self.append(item)
    def isEmpty(self):
        return not self


You are right to use composition instead of inheritance, because inheritance brings methods in that you don't want to expose.

class Stack:
  def __init__(self):
    self.__storage = []

  def isEmpty(self):
    return len(self.__storage) == 0

  def push(self,p):
    self.__storage.append(p)

  def pop(self):
    return self.__storage.pop()

This way your interface works pretty much like list (same behavior on pop for example), except that you've locked it to ensure nobody messes with the internals.


I won't talk about the list structure as that's already been covered in this question. Instead I'll mention my preferred method for dealing with stacks:

I always use the Queue module. It supports FIFO and LIFO data structures and is thread safe.

See the docs for more info. It doesn't implement a isEmpty() function, it instead raises a Full or Empty exception if a push or pop can't be done.


Stack follows LIFO mechanism.You can create a list and do a normal append() to append the element to list and do pop() to retrieve the element out of the list which you just inserted.


Here is an example for stack class

class Stack(object):

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

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

   def pop(self):
       return self.items.pop()

   def peek(self):
       return self.items[-1]

   def isEmpty(self):
       return len(self.items) == 0


    class Stack:
        def __init__(self):
            self.items=[]

        def isEmpty(self):
            return self.items==[]

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

        def pop(self):
            return self.items.pop()

        def size(self):
            return len(self.items)

        def peek(self):
            return self.items[-1]

Create a stack

To create a new stack we can simply use Stack()

for example:

     s=Stack()

"s" is the name of new stack

isEmpty

By using isEmpty() we can check our stack is empty or not

for example:

we have two stacks name s1=(0,1,4,5,6) and s2=()

if we use print(s1.isEmpty()) it will return False

if we use print(s2.isEmpty()) it will return True

push

By using push operation we can add items to top of the stack

we can add "6" to the stack name "s" using

    s.push(6)

pop

we can use pop operation to remove and return the top item of a stack

if there is a stack name "s" with n amount items (n>0) we can remove it's top most item by using

    s.pop()

size

This operation will return how many items are in the stack

if there is a stack name "s" s=(1,2,3,4,5,3)

    print(s.size())

will return "6"

peek This operation returns the top item without removing it

    print(s.peek())

"we can print items of the stack using print(s.items)"


class Stack:
    def __init__(self):
        self.stack = []
    def pop(self):
        if self.is_empty():
            return None
        else:
            return self.stack.pop()
    def push(self, d):
        return self.stack.append(d)
    def peek(self):
        if self.is_empty():
            return None
        else:
            return self.stack[-1]
    def size(self):
        return len(self.stack)
    def is_empty(self):
        return self.size() == 0


class stack:

def __init__(self,n):##constructor

    self.no = n ##size of stack

    self.Stack = [] ##list for store stack items

    self.top = -1

def push(self):##push method
    if self.top == self.no - 1 :##check full condition
        print("Stack Overflow.....")
    else:
        n = int(input("enter an element :: "))
        self.Stack.append(n) ## in list add stack items use of append method
        self.top += 1##increment top by 1

def pop(self):## pop method

    if self.top == -1: #check empty condition
        print("Stack Underflow....")
    else:
        self.Stack.pop()## delete item from top of stack using pop method
        self.top -= 1 ## decrement top by 1

def peep(self): ##peep method
    print(self.top,"\t",self.Stack[-1]) ##display top item

def disp (self): #display method
    if self.top == -1:# check empty condition
        print("Stack Underflow....")
    else:
        print("TOP \tELEMENT")
        for i in range(self.top,-1,-1): ## print items and top
            print(i," \t",self.Stack[i])

n = int(input("Enter Size :: ")) # size of stack

stk = stack(n) ## object and pass n as size

while(True): ## loop for choice as a switch case

print(" 1: PUSH ")
print(" 2: POP ")
print(" 3: PEEP ")
print(" 4: PRINT ")
print(" 5: EXIT ")

option = int(input("enter your choice :: "))

if option == 1:
    stk.push()

elif option == 2:
    stk.pop()

elif option == 3:
    stk.peep()

elif option == 4:
    stk.disp()

elif option == 5:
    print("you are exit!!!!!")
    break
else:
    print("Incorrect option")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜