Python OOP: Exercise-9 with Solution
Write a Python program to create a class representing a stack data structure. Include methods for pushing, popping and displaying elements.
Sample Solution:
Python Code:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("Cannot pop from an empty stack.")
def is_empty(self):
return len(self.items) == 0
def display(self):
print("Stack items:", self.items)
# Example usage
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
stack.push(40)
stack.push(50)
stack.display()
popped_item = stack.pop()
print("Popped item:", popped_item)
popped_item = stack.pop()
print("Popped item:", popped_item)
stack.display()
Sample Output:
Stack items: [10, 20, 30, 40, 50]
Popped item: 50
Popped item: 40
Stack items: [10, 20, 30]
Explanation:
In this above exercise,
We define a Stack class representing a stack data structure. It has an attribute called items, which is initially an empty list.
The "push()" method takes an item as an argument and appends it to the items list, effectively adding it to the top of the stack.
The "pop()" method removes and returns the topmost item from the stack. It checks if the stack is empty before popping an item. If the stack is empty, it raises an IndexError with an appropriate error message.
The "is_empty()" method checks if the stack is empty by examining the length of the items list.
The "display()" method simply prints the stack elements.
In the example usage section, we create an instance of the Stack class called stack. We push and pop several items onto the stack using the "push()" and "pop()" methods. We then display the stack elements using the "display()" method.
Flowchart:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Shopping cart class with item management and total calculation.
Next: Queue class with enqueue and dequeue methods.
What is the difficulty level of this exercise?
Medium
Python: Tips of the Day
Access an Element in a Sequence Using the Reverse Index:
>>> a = 'Hello World!'
>>> # instead of using a[len(a)-1]
>>> a[-1]
>>> # in combination with slicing
>>> a[-5:-1]
'orld'
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us
at Facebook