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

USING PYTHON!! A stack is a sequence container type that, like a queue, supports

ID: 3662457 • Letter: U

Question

USING 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. A stack is often referred to as a list-in first-out (LIFO) container because the last item inserted is the first removed. Implement a Stack class. It should support the following methods/functions:

_init__ - Can construct either an empty stack, or initialized with a list of items, the first item is at the bottom, the last is at the top.

push() – take an item as input and push it on the top of the stack

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

isEmpty() – returns True if the stack is empty, False otherwise

[] – return the item at a given location, [0] is at the bottom of the stack

len() – return length of the stack

The object is to make this client code work:

'''

>>> s = Stack()

>>> s.push('apple')

>>> s

Stack(['apple'])

>>> s.push('pear')

>>> s.push('kiwi')

>>> s

Stack(['apple', 'pear', 'kiwi'])

>>> top = s.pop()

>>> top

'kiwi'

>>> s

Stack(['apple', 'pear'])

>>> len(s)

2

>>> s.isEmpty()

False

>>> s.pop()

'pear'

>>> s.pop()

'apple'

>>> s.isEmpty()

True

>>> s = Stack(['apple', 'pear', 'kiwi'])

>>> s = Stack(['apple', 'pear', 'kiwi'])

>>> s[0]

'apple'

>>>

'''

Explanation / Answer

class Stack():

def __init__(self):

    self.items = []

   

def isEmpty(self):

    return self.items == []

   

def push(self, item):

    return self.items.append(item)

def pop(self):

    return self.items.pop()

def getElements(self):

    return self.items

stack = Stack()

stack.push('apple')

stack.push('pear')

stack.push('kiwi')

print stack.getElements()

top = stack.pop()

print top

print stack.getElements()

print stack.isEmpty()

top1 = stack.pop()

print top1

top2 = stack.pop()

print top2

print stack.getElements()

print stack.isEmpty()