# Stack.py Copyright (c) Kari Laitinen # http://www.naturalprogramming.com # 2006-05-22 File created. # 2022-12-27 Converted to Python 3. class Stack : def __init__( self ) : self.stack_memory_space = [] def push( self, item_to_the_stack ) : # We do not need to increase the memory space because # a dynamic list is used to store the values that are # pushed to the stack. The memory space grows automatically # when necessary. self.stack_memory_space.append( item_to_the_stack ) def pop( self ) : if len( self.stack_memory_space ) == 0 : print( "\n ERROR: Attempt to pop on empty stack !" ) item_from_the_stack = -1 else : # The standard list method pop() is used to pop the last element item_from_the_stack = self.stack_memory_space.pop() return item_from_the_stack def stack_is_not_empty( self ) : return len( self.stack_memory_space ) > 0 # The main program begins. test_stack = Stack() print( "\n Let's test a stack. Please, type in integers." \ "\n I will push those numbers onto a stack, and later" \ "\n take them away from the stack. I will stop reading" \ "\n numbers when you type in a zero." \ "\n Please, press after each number. \n" ) value_to_the_stack = -1 # a value other than zero while value_to_the_stack != 0 : print( " Give a number: ", end="" ) value_to_the_stack = int( input() ) test_stack.push( value_to_the_stack ) print( "\n The numbers popped from the stack are:\n" ) while test_stack.stack_is_not_empty() : value_popped_from_the_stack = test_stack.pop() print( " %d" % value_popped_from_the_stack, end="" ) print( "" )