I have 2 issues with the code below:
Should I throw an exception if pop()
class Stack:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self , item):
self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
return self.items[-1]
Create a stack
To create a new stack we can simply use Stack()
for example:
s=Stack()
"s" is the name of new stack
isEmpty
By using isEmpty()
we can check our stack is empty or not
for example:
we have two stacks name s1=(0,1,4,5,6) and s2=()
if we use print(s1.isEmpty())
it will return False
if we use print(s2.isEmpty())
it will return True
push
By using push operation we can add items to top of the stack
we can add "6" to the stack name "s" using
s.push(6)
pop
we can use pop operation to remove and return the top item of a stack
if there is a stack name "s" with n amount items (n>0) we can remove it's top most item by using
s.pop()
size
This operation will return how many items are in the stack
if there is a stack name "s" s=(1,2,3,4,5,3)
print(s.size())
will return "6"
peek This operation returns the top item without removing it
print(s.peek())
"we can print items of the stack using print(s.items)
"