Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python a stack is a sequence container type that, like a queue, supports very re

ID: 3763589 • Letter: P

Question

Python

a stack is a sequence container type that, like a queue, supports very restrictive access methods: All insertions and removals are from one end of the stack, typically referred to as the top of the stack. Implement container class Stack that implements a stack. It should be a subclass of object. support the len() overloaded operator, and support the methods:

-push() : Take an item as input and push it on top of the stack

-pop(): remove and return the item at the top of the stack

-isEmpty() : Return True if the stack is empty, False otherwise

You should also insure that the stack can be printed as shown. A stack is often referred to as a last-in first-out(LIFO) container because the last item inserted is the first removed.

>>> s=Stack()

>>> s.push('plate 1')

>>>s.push('plate 2')

>>>s.push('plate 3')

>>>s

['plate 1','plate 2', 'plate 3']

>>>len(s)

3

>>>s.pop()

'plate 3'

>>>s.pop()

'plate 2'

>>>s.pop()

'plate 1'

>>>s.isEmpty()

True

Explanation / Answer

See the below python code for implementing container class Stack that implements a stack

from pythonds.basic.stack import Stack
class Stack:
    def __init__(self):
        self.items = []
  
    def isEmpty(self):
        return self.items == []
  
    def push(self, item):
        self.items.insert(0,item)
  
    def pop(self):
        return self.items.pop(0)
  
    def peek(self):
        return self.items[0]

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

  
    s = Stack()
    s.push('plate 1')                # Insert Plate 1 into Stack
    s.push('plate 2')                # Insert Plate 2 into Stack
    s.push('plate 3')                # Insert Plate 3 into Stack
    print(s.size())                  # length of the stack
    print(s.pop())                   # Pop the Plate 1 from the Stack
    print(s.pop())                   # Pop the Plate 1 from the Stack
    print(s.pop())                   # Pop the Plate 1 from the Stack
    print(s.isEmpty())               # Will return true if it is empty otherwise false

Ouput is:

3
plate 3
plate 2
plate 1
True