In: Computer Science
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'
>>>
'''
use python3.7
>>> 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'
>>>
check that Stacks constructed without a list remain
distinct
if you receive an error on s2 then you probably need to use a
default argument of None in __init__
(see the Queue class developed in class for an example)
>>> s = Stack()
>>> s.push('apple')
>>> s
Stack(['apple'])
>>> s2 = Stack()
>>> s2.push('pear')
>>> s2 # if this fails - see the TEST file for
explanation
Stack(['pear'])
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
class Stack:
# Constructor
# 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
def __init__(self, items=None):
if items is None:
self.data = []
else:
self.data = items
# take an item as input and push it on the top of the stack
def push(self,item):
self.data.append(item)
# remove and return the item at the top of the stack
def pop(self):
return self.data.pop(-1)
# returns True if the stack is empty, False otherwise
def isEmpty(self):
return len(self.data)==0
# gives the length of the stack
def __len__(self):
return len(self.data)
# gives the item at location
def __getitem__(self, index):
return self.data[index]
# string representation
def __str__(self):
return 'Stack('+str(self.data)+')'
def __repr__(self):
return self.__str__()
==============================
SCREENSHOT:

OUTPUT:

