Skip to main content

Stack Abstract Data Type with implementation in Python as Arrays

Stack is a collection of objects where the elements are inserted and removed based on the principle of LIFO (Last In First Out).

Common applications for Stack ADT is in text editors for managing undo operation.

Github Link : stacks.py & test_stacks.py

Implementation using Python

# File : stacks.py
# Stack ADT implementation using Lists as underlying data structures
# S.push(e)    : Add element 'e' to the top of Stack S
# S.pop()      : Remove element from the top of Stack S and return the removed element, error if empty
# S.top()      : Return the reference of the top element of S without removing it, error if empty
# S.isEmpty()  : Return True if stack is empty
# len(S)       : Return number of elements in Stack S
 
class EmptyStackException(Exception):
    pass

class StacksList(object):
    def __init__(self):
        self._data = []

    def push(self,e):
        self._data.append(e)

    def pop(self):
        if self.isEmpty():
            raise EmptyStackException("No Elements in Stack")
        return self._data.pop()

    def top(self):
        if self.isEmpty():
            raise EmptyStackException("No Elements in Stack")
        return self._data[-1]
    
    def isEmpty(self):
        return len(self._data) == 0

    def __len__(self):
        return len(self._data)

Testcase(s) for Stack

import unittest
from stacks import StacksList, EmptyStackException

class TestStacks(unittest.TestCase):
    def setUp(self):
        self.S = StacksList()
  
    def test_emptyStack(self):
        self.assertEqual(len(self.S),0)
        self.assertTrue(self.S.isEmpty())
        with self.assertRaises(EmptyStackException) as cm:
            self.S.pop()
        expected_msg = "No Elements in Stack"
        self.assertEquals(cm.exception.message, expected_msg)
        with self.assertRaises(EmptyStackException) as cm:
            self.S.top()
        expected_msg = "No Elements in Stack"
        self.assertEquals(cm.exception.message, expected_msg)

    def test_push_pop_top_len(self):
        self.S.push('A')
        self.S.push('B')
        self.assertEqual(len(self.S),2)
        self.assertFalse(self.S.isEmpty())
        self.assertEqual(self.S.top(),'B')
        self.assertEqual(len(self.S),2)
        self.assertEqual(self.S.pop(),'B')
        self.assertEqual(len(self.S),1)
        self.S.push('C')
        self.assertEqual(self.S.pop(),'C')
        self.assertEqual(self.S.pop(),'A')
        self.assertEqual(len(self.S),0)

if __name__ == '__main__':
    unittest.main(verbosity=2)

Comments