Write a program in PYTHON that uses the Stack implementation given to you in sta
ID: 3664658 • Letter: W
Question
Write a program in PYTHON that uses the Stack implementation given to you in stack.py to reverse a String. The program should ask the user for a String, and should then display the reversed String. The Stack class must be used to reverse the String, one character at a time.
#file-stack.py
# A Stack implementation
class Stack:
def __init__(self):
self.__items = []
def push(self, item):
self.__items.append(item)
def pop(self):
return self.__items.pop()
def peek(self):
return self.__items[len(self.__items)-1]
def is_empty(self):
return len(self.__items) == 0
def size(self):
return len(self.__items)
Explanation / Answer
# This function is used to create an empty stack. It initializes size of stack as 0
def createStack():
stack=[]
return stack
# This function is used to determine the size of the stack.
def size(stack):
return len(stack)
# This function checks if the stack is empty.The stack is empty if the size is 0
def isEmpty(stack):
if size(stack) == 0:
return true
# This function is used to add an item to stack . It increases size by 1
def push(stack,itemone):
stack.append(itemone)
# This function is used to remove an item from stack. It decreases size by 1
def pop(stack):
if isEmpty(stack): return
return stack.pop()
# we will create a stack based function to reverse a string
def reverse(stringone):
p = len(stringone)
# This will create an empty stack
stack = createStack()
# Now we will push all characters of string to stack one by one.
for i in range(0,p,1):
push(stack,stringone[i])
# now we will make the string empty since all characters are saved in stack
stringone=""
# Finally we will pop all characters of string and put them back to string .This will b in reverse order an it pops from the top.
for i in range(0,p,1):
stringone+=pop(stack)
return stringone
# The driver program to test above functions
stringone="HelloPeople"
stringone = reverse(stringone)
print(" The reversed string is " + stringone)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.