'''stack4.py Jed Yang, 2016-11-06 A possibly silly implementation of a stack. ''' class Stack: def __init__(self): '''Initialize a new empty stack.''' self.items = [] def push(self, item): '''Add a new item to the stack.''' self.items.append([item, True]) # think of True as "in the stack" def pop(self): '''Remove and return from the stack the item that was last added.''' i = len(self.items) while True: i = i - 1 if self.items[i][1]: # find something in the stack self.items[i][1] = False # declare it not in the stack return self.items[i][0] def isEmpty(self): '''Check whether the stack is empty.''' for item in self.items: if item[1]: # found something in the stack return False return True # didn't find anything def reportStats(self): '''Prints out some information.''' pops = [] for item in self.items: if not item[1]: pops.append(item[0]) print('Stack Report') print('============') print('Total number of pushes:', len(self.items)) print('Total number of pops:', len(pops)) print('Popped items:', str(pops)) def __str__(self): '''Return a string representation, for example when print() is called.''' answer = [] for item in self.items: if item[1]: answer.append(item[0]) # only report items in the stack return str(answer) # This (possibly silly) implementation of Stack is more complicated. It seems # to retain information about every item ever pushed. It uses a flag to # remember if the item has been popped out. # It adds a reportStats() method that makes a report of sorts. # The point is that, if the implementation is correct (the behaviour of push(), # pop(), etc. fulfil the requirement of what a stack should do), then we can # use it without caring about how the data is actually stored. This is a kind # of "encapsulation": hiding details behind the scenes. # Perhaps I will use this Stack implementation when debugging a program that # uses stacks. This way I can take advantage of the new reportStats() method. # When I am done, maybe I will switch back to a more standard, efficient # implementation of Stack (e.g., stack.py). Of course, I need to make sure I # am no longer calling reportStats() anywhere. This is not actually the best # way of doing things. I am just trying to illustrate the point that we can # implement a stack many different ways.