Skip to content

Instantly share code, notes, and snippets.

@Abhayparashar31
Created September 30, 2020 03:07
Show Gist options
  • Save Abhayparashar31/c18fccbf3a6ed7b1db46d03cac4ae558 to your computer and use it in GitHub Desktop.
Save Abhayparashar31/c18fccbf3a6ed7b1db46d03cac4ae558 to your computer and use it in GitHub Desktop.
class Stack():
def __init__(self):
self.items = [] ## Empty list intilize
def push(self,item):
self.items.append(item) ## simple appending to list
def pop(self):
return self.items.pop() ## Removing top element of the stack
def is_empty(self):
return self.items==[] ### Checking whether the stack is empty or not
def peek(self):
if not self.is_empty():
return self.items[-1] ## returnign top element using [-1]=last element
def show_stack(self):
return self.items ## Printing all the items
obj = Stack() ## Creating obj for class stack
num = int(input("enter the number of commands")) ## Taking number of commands push 10
for i in range(num): ## Running the loop till the length of commands
command = input().split(" ") ## Spliting the command with space
if command[0]=='push': ## IF index 0 is push then call push method
obj.push(int(command[1]))
print(obj.show_stack())
elif command[0]=='pop':
obj.pop()
print(obj.show_stack())
elif command[0]=='peek':
print(obj.peek())
elif command[0]=='show':
print(obj.show_stack())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment