Question: class Stack: def _ _ init _ _ ( self , max _ size = 5 ) : self.top = - 1 # Represents the
class Stack:
def initself maxsize:
self.top # Represents the index of the top element in the stack.
self.maxsize maxsize # Maximum size of the stack.
self.items for x in rangemaxsize # The array to store stack items.
def isemptyself:
# Check if the stack is empty.
return self.top
def isfullself:
# Check if the stack is full reached its maximum size
return self.top self.maxsize
def pushself item:
if not self.isfull:
# Add an item to the top of the stack.
self.top
self.itemsselftop item
else:
raise StackFullExceptionStack is full!"
def popself:
if not self.isempty:
# Remove and return the top item from the stack.
itemstr self.itemsselftop
self.top
return itemstr
else:
raise StackEmptyExceptionStack is empty!"
def peekself:
if not self.isempty:
# Return the top item without removing it
return self.itemsselftop
else:
raise StackEmptyExceptionStack is empty!"
def sizeself:
# Return the current size of the stack.
return self.top
def printstackupself:
# Return a string representation of the stack, with each item on a new line.
stackstr
for i in rangeselftop, :
stackstr self.itemsi
return stackstr
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
