In: Computer Science
All code should be in Python 3. Implement the Stack Class, using the push, pop, str, init methods, and the insurance variable 'list'.
We can't use list as a variable a it is a predefined function in python. So, it will show error.
---------------------Program-----------------
import random
class Stack():
# constructor
def __init__(self):
self._elements = []
self._count = 0
# push elt into the stack
def push(self, elt):
self._elements.append(elt)
self._count += 1
# pop top most element from the stack
def pop(self):
# if stack is empty
if self.is_empty():
return 'Stack Empty!'
# decrement the count of elements in the stack
self._count -= 1
# return the top most element in th list
return self._elements.pop()
# get the top most element from the stack
def top(self):
if self.is_empty():
return 'Stack Empty!'
else:
return self._elements[self._count - 1]
# return true if the stack is empty, false otherwise
def is_empty(self):
return self._count == 0
# get the size of stack
def size(self):
return self._count
def __str__(self):
# if stack is empty
if self.is_empty() == True:
return '()'
ans = '('
for i in range(0, self._count - 1):
ans += str(self._elements[i]) + ', '
ans += str(self._elements[self._count - 1]) + ')'
return ans
def __repr__(self):
if self.is_empty() == True:
return 'Stack List ()'
ans = 'Stack List ('
for i in range(0, self._count - 1):
ans += str(self._elements[i]) + ', '
ans += str(self._elements[self._count - 1]) + ')'
return ans
s = Stack()
s.push(random.randint(-100, 100))
s.push(random.randint(-100, 100))
s.push(random.randint(-100, 100))
s.push(random.randint(-100, 100))
print(s)
print(s.__repr__())
print('\nTop Most Element :', s.top())
print('\nPopping Stack ...')
while not s.is_empty():
print(s.pop())
Sample Output