A stack is a last-in-first-out (LIFO) data structure. It has three primitive operations:
In Python, a stack is implemented using a list object.
list.append(item)
list.pop()
list[-1]
The following illustration explains the concept:
The following code explains how to implement a stack in python:
class Stack:def __init__(self):self.items = []def is_empty(self):return len(self.items) == 0def push(self, item):self.items.append(item)def pop(self):if not self.is_empty():return self.items.pop()else:print("Stack is empty")def peek(self):if not self.is_empty():return self.items[-1]else:print("Stack is empty")def size(self):return len(self.items)# Example usage:if __name__ == "__main__":stack = Stack()stack.push("a")stack.push("b")stack.push("c")print("Stack:", stack.items)print("Number of items in stack", stack.size())print("The top value in the stack is:", stack.peek())value_popped = stack.pop()print("Value removed from Stack:", value_popped)print("Remaining elements in Stack are:", stack.items)
The above example uses a list to store the elements of the stack.
is_empty()
: Checks if the stack is empty.
push(item)
: Adds an item to the top of the stack.
pop()
: Removes and returns the item at the top of the stack.
peek()
: Returns the item at the top of the stack without its removal
size()
: Returns the number of elements present in the stack.
Write a Python program to reverse a string using a stack data structure. The program should take this string Educative
and utilize a stack to reverse the order of characters in the string. Please use the widget provided below to write the program and execute the program by clicking on the "Run" button.
If you feel stuck at any point click the "Solution" button to see the solution of the problem.
class Stack:def __init__(self):self.items = []def is_empty(self):return len(self.items) == 0def push(self, item):self.items.append(item)def pop(self):if not self.is_empty():return self.items.pop()else:print("Stack is empty")def size(self):return len(self.items)def reverse_string(input_string):"""Function to reverse a string using a stack."""stack = Stack()# Push each character onto the stack# WRITE YOUR CODE HERE# Pop each character from the stack to get reversed orderwhile not stack.is_empty():#WRITE YOUR CODE HEREreturn reversed_stringdef main():"""Main function to accept user input and reverse the string."""input_string = "Educative"#WRITE YOUR CODE HEREprint("Reversed string:", reversed_string)if __name__ == "__main__":main()
Free Resources