Python

Using Stacks to Reverse Four Letters

This code can be used to add four letters to a stack and get them in reverse order

class Stack:
    def __init__(self):
        self.items = [] #create new list with no items

    def __repr__(self):
        return repr(self.items) #define what to return is the stackname is called

    def isEmpty(self):
        return self.items == [] #check whether list if empty and retuen T or F

    def size(self):
        return len(self.items) #return size of stack (= length of list)

    def push(self,val):
        self.items.append(val) #add the argument pass to the end of list

    def pop(self):
        return self.items.pop() #return the last item in list because index not specified

    def peek(self):
        return self.items[-1] #return last item (-1 because from right indices are negative)

#Create the stack
thestack=Stack()

thestack.push('A')  #add A to stack
thestack.push('B')  #add B to stack
thestack.push('C')  #add C to stack
thestack.push('D')  #add D to stack

print(thestack)

print (thestack.pop())  #pop the top item ie D
print (thestack.pop())  #pop the top item ie C
print (thestack.pop())  #pop the top item ie B
print (thestack.pop())  #pop the top item ie A

 


The owner of [www.ksoftlabs.com] will not be liable for any errors or omissions in this information nor for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display or use of this information.
This terms and conditions are subject to change at anytime with or without notice.

Kavinda

Proud UCSCian | Proud Devan | Computer Geek | Superman | Love Chess & Programming

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.