[Data Structure] Stack Implementation in Python

时间:2022-07-22 08:50:12

We can realize a Stack as an adaptation of a Python List.

S.push(e)=L.append(e)

S.pop()=L.pop()

S.top()=L[-1]

S.len()=len(L)

S.is_empty=(len(L)==0)

class Empty(Exception):
pass class ArrayStack:
"""LIFO Stack implementation using Python""" def __init__(self):
self._data=[] def __len__(self):
return len(self._data) def is_empty(self):
return len(self._data)==0 def push(self,e):
self._data.append(e) def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data.pop() def top(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data[-1]