In: Computer Science
"""stack.py implements stack with a list"""
class Stack(object):
def __init__(self): #creates an empty stack. O(1)
self.top = -1 #the index of the top element of the stack. -1: empty
stack
self.data = []
def push(self, item): # add item to the top of the stack.
O(1)
self.top += 1
self.data.append(item)
def pop(self): # removes and returns the item at the top
O(1)
self.top -=1
return self.data.pop()
def peek(self): # returns the item at the top O(1)
return self.data[len(self.data)-1]
def isEmpty(self): return self.top == -1 #return
len(self.data)==0
def __len__(self): return self.top+1 #return len(self.data)
def __str__(self): return " ".join([str(x) for x in self.data])
#to do: add a main method to test the stack.
Below is the fully implemented code and added main method to test the stack
"""stack.py implements stack with a list"""
class Stack(object):
def __init__(self):
self.top = -1
self.data = []
def push(self, item):
self.top += 1
self.data.append(item)
def pop(self): # removes and returns the item at the top
O(1)
self.top -=1
return self.data.pop()
def peek(self): # returns the item at the top O(1)
return self.data[len(self.data)-1]
def isEmpty(self):
return self.top == -1 #return len(self.data)==0
def __len__(self):
return self.top+1 #return len(self.data)
def __str__(self):
return " ".join([str(x) for x in self.data])
#to do: add a main method to test the stack.
s=Stack()
print(s.isEmpty()) # Return true if stack is empty and false if stack is not empty
s.push(4) # To push element 4 in stack
s.push(5) # To push element 5 in stack
print(s.peek()) # To see the top element in stack
s.push(6) # To push element 6 in stack
print(s.isEmpty()) # Return true if stack is empty and false if stack is not empty
s.push(9.2) # To push element 9.2 in stack
print(s.pop()) # To pop element of stack
print(s.pop()) # To pop element of stack
CONCEPT : I have just called the object of Stack class and make a object "s" with s i have c=made call to push() and and pop() and isEmpty() and peek() function hence these will return it's output once you execute the code.