World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Designed by IITians, only for AI Learners.
New to InsideAIML? Create an account
Employer? Create an account
Implementation of stack :
The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where items are added to and removed from the end called the “top.” Stacks are ordered LIFO. The stack operations are given below.
class Stack(object): def __init__(self): self.items = [] def isEmpty(self): # Check Stack is Empty or not return True or False return self.items == [] def push(self, item): # Insert/push Element in stack self.items.append(item) def pop(self): # Delete/pop element from stack return self.items.pop() def peek(self): # Top of the stack return self.items[len(self.items)-1] def size(self): # Size of Stack return len(self.items) def print(self): # Print stack return self.items
In [47]:s = Stack()
In [49]: s.push(1) s.push(2) s.push(3) s.push('a') s.push(-2)
In [50]: s.print() Out[50]: [1, 2, 3, 1, 2, 3, 'a', -2]
In [51]: s.pop() Out[50]: -2
In [52]: s.print() Out[50]: [1, 2, 3, 1, 2, 3, 'a']
In [53]: s.peek() Out[50]: a
In [54]: s.size() Out[50]: 7
In [55]: s.isEmpty() Out[50]: False