[Tutor] stack class

Christopher Spears cspears2002 at yahoo.com
Sat Jul 12 01:54:18 CEST 2008


For another Core Python Programming question, I created a stack class.  I then put the class into a script to test it:

#!/usr/bin/python

class Stack(list):
    def isempty(self):
        length = len(self)
        if length == 0:
	    return True
	else:
	    return False
	    
    def peek(self):
        length = len(self)
	if length == 0:
	    return 0
	else:
	    last_index = length - 1
            return self[last_index]
    
    def stackpop(self):
        length = len(self)
	if length == 0:
	    print "Empty list!"
	else:
	    last_index = length - 1
	    stackpop_val = self[last_index]
	    self = self[:last_index]
	    return stackpop_val
    
    def push(self, value):
        return self.append(value)
	
if __name__ == '__main__':
    x = True
    stack = Stack()
    print "Pick an option to modify stack: "
    while x == True:
	print "1) Peek at the last value"
	print "2) Pop off the last value"
	print "3) Push a value on the stack"
	print "4) Quit Program"
	choice_string = raw_input("Make a choice: ")
    
        try:
            choice = int(choice_string)
        except ValueError:
            sys.exit("Not an integer!  Goodbye!")
  
        if choice == 1:
	    if stack.isempty():
	        print "Stack is empty"
	    else:
                peek_val = stack.peek()
	        print peek_val
        elif choice == 2:
	    if "pop" in dir(list):
                pop_val = stack.pop()
	        print pop_val
	    else:
	        pop_val = stack.stackpop()
		print pop_val
        elif choice == 3:
	    push_val = raw_input("Push this value on stack: ")
            stack.push(push_val)
	    print stack
        elif choice == 4:
            print "Goodbye!"
	    x = False
        else:
	    x = False
            sys.exit("Wrong response Goodbye!")

According to the question, I should test if the pop() function is available.  If that function is not available, the stack should use a pop() method of my own design.  I think I solved the problem, but I am not sure how to test it because Python 2.4 is installed on my computer.


      


More information about the Tutor mailing list