Question: class Stack: def _ _ init _ _ ( self , max _ size = 5 ) : self.top = - 1 # Represents the

class Stack:
def __init__(self, max_size=5):
self.top =-1 # Represents the index of the top element in the stack.
self.max_size = max_size # Maximum size of the stack.
self.items =["" for x in range(max_size)] # The array to store stack items.
def is_empty(self):
# Check if the stack is empty.
return self.top ==-1
def is_full(self):
# Check if the stack is full (reached its maximum size).
return self.top == self.max_size -1
def push(self, item):
if not self.is_full():
# Add an item to the top of the stack.
self.top +=1
self.items[self.top]= item
else:
raise StackFullException("Stack is full!")
def pop(self):
if not self.is_empty():
# Remove and return the top item from the stack.
item_str = self.items[self.top]
self.top -=1
return item_str
else:
raise StackEmptyException("Stack is empty!")
def peek(self):
if not self.is_empty():
# Return the top item without removing it.
return self.items[self.top]
else:
raise StackEmptyException("Stack is empty!")
def size(self):
# Return the current size of the stack.
return self.top +1
def print_stack_up(self):
# Return a string representation of the stack, with each item on a new line.
stack_str =""
for i in range(self.top, -1,-1):
stack_str += self.items[i]+"
"
return stack_str

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!