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

Programming Language Python: A \"Stack\" is an abstract data type for storing a

ID: 3871404 • Letter: P

Question

Programming Language Python:

A "Stack" is an abstract data type for storing a collection of items, where items are both added and removed from one end of the collection. The methods for adding and removing items from a stack are traditionally called "push()" and "pop()" respectively. A method called "peek()" returns the value on the top of the stack, but does not remove it from the stack. A "size()" method returns the number of items on the stack, and a method "is_empty()" returns a boolean indicating if the stack is empty.

For this exercise, you will provide a complete implementation of the Stack ADT. You can implement the Stack ADT in any way that you like, but using a Python list to store the items is certainly the simplest way.

The method names are given below as a guide to help you:

For example:

Test Result
  s = Stack()  print(s.is_empty())  
  True  
  s = Stack()  s.push(1)  s.push(2)  s.push(3)  s.push(4)  while not s.is_empty():    print(s.pop())  
  4  3  2  1  

Explanation / Answer

#!usr/bin/python

class stack:
    def __init__(self):
         self.data = []
        
    def is_empty(self):
        if len(self.data) == 0 :
           return True
        else:
           return False

    def push(self, a):
        self.data.append(a)
       

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


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

    def size(self):
       return len(self.data)
      
s = stack()
print(s.is_empty())
s.push(1)
s.push(2)
s.push(3)
s.push(4)
print(s.data)
while not s.is_empty():
print(s.pop())