I have written a simple stack implementation and would like some feedback as to what I could improve in my code and coding practices.
# A simple stack in python with ints.
class stack():
def __init__(self, maxSize=16):
self.maxSize = maxSize
self.data = []
def isEmpty(self):
if len(self.data) == 0:
return True
else:
return False
def isFull(self):
if len(self.data) == self.maxSize:
return True
else:
return False
def push(self, data):
if not self.isFull():
self.data.append(data)
return "OK"
else:
return "ERR_Stack_Full"
def pop(self):
if not self.isEmpty():
output = self.data[len(self.data) -1]
del self.data[len(self.data) -1]
return output, "OK"
else:
return "ERR_Stack_Empty"
def npop(self, n):
output = []
if len(self.data) >= n:
for i in range(n):
output.append(self.pop()[0])
return output, "OK"
Based on the input given here is my modified code (Sorry about the entire thing being indented, the code sample button was being difficult):
class EmptyStackError(Exception):
def __init__(self):
super().__init__("Stack is empty: cannot pop from an empty stack!")
class FullStackError(Exception):
def __init__(self):
super().__init__("Stack is full: cannot push to a full stack!")
# A simple stack in python with ints.
class Stack():
def __init__(self, max_size=16):
self.max_size = max_size
self.data = []
def is_empty(self):
if len(self.data) == 0:
return True
def is_full(self):
if len(self.data) == self.max_size:
return True
def push(self, data):
if not self.is_full():
self.data.append(data)
return data
else:
raise FullStackError()
def pop(self):
if not self.is_empty():
output = self.data[len(self.data) -1]
del self.data[len(self.data) -1]
return output
else:
raise EmptyStackError()