Compare commits
7 Commits
511dd6a9db
...
05d5b66dec
| Author | SHA1 | Date | |
|---|---|---|---|
| 05d5b66dec | |||
| d876bc9a73 | |||
| 9e8153eb1f | |||
| b2ecff6a6b | |||
| e25318b336 | |||
| bb366686c1 | |||
| 5b3f9eff6b |
@@ -19,7 +19,9 @@ class Stack[T]:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
pass
|
||||
''' initializes an empty stack '''
|
||||
self._data = LinkedList()
|
||||
|
||||
def __len__(self) -> int:
|
||||
''' allows the len function to be called using an ArrayStack object, e.g.,
|
||||
stack = ArrayStack()
|
||||
@@ -27,7 +29,7 @@ class Stack[T]:
|
||||
Returns:
|
||||
number of elements in the stack, as an integer
|
||||
'''
|
||||
pass
|
||||
return len(self._data)
|
||||
|
||||
def push(self, item: T) -> None:
|
||||
''' pushes a given item of arbitrary type onto the stack
|
||||
@@ -36,7 +38,7 @@ class Stack[T]:
|
||||
Returns:
|
||||
None
|
||||
'''
|
||||
pass
|
||||
self._data.insert_head(item)
|
||||
|
||||
def pop(self) -> T:
|
||||
''' removes the topmost element from the stack and returns that element
|
||||
@@ -45,7 +47,9 @@ class Stack[T]:
|
||||
Raises:
|
||||
EmptyError exception if the stack is empty
|
||||
'''
|
||||
pass
|
||||
if self.is_empty():
|
||||
raise EmptyError("Stack is empty")
|
||||
return self._data.remove_head()
|
||||
|
||||
def peek(self) -> T:
|
||||
''' returns the topmost element from the stack without modifying the stack
|
||||
@@ -54,14 +58,16 @@ class Stack[T]:
|
||||
Raises:
|
||||
EmptyError exception if the stack is empty
|
||||
'''
|
||||
pass
|
||||
if self.is_empty():
|
||||
raise EmptyError("Stack is empty")
|
||||
return self._data.get_head()
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
''' indicates whether the stack is empty
|
||||
Returns:
|
||||
True if the stack is empty, False otherwise
|
||||
'''
|
||||
pass
|
||||
return len(self._data) == 0
|
||||
|
||||
def __str__(self) -> str:
|
||||
''' returns an str implementation of the Stack '''
|
||||
@@ -69,9 +75,40 @@ class Stack[T]:
|
||||
return str(self._data)
|
||||
|
||||
def main():
|
||||
# add your tests here!
|
||||
'''test functions'''
|
||||
s = Stack() # I added this so stack doesnt need to be reinitialized for each test
|
||||
|
||||
assert len(s) == 0
|
||||
assert s.is_empty() is True
|
||||
|
||||
s.push(10)
|
||||
assert len(s) == 1
|
||||
assert s.peek() == 10
|
||||
|
||||
s.push(20)
|
||||
s.push(30)
|
||||
assert len(s) == 3
|
||||
assert s.peek() == 30
|
||||
|
||||
assert s.pop() == 30
|
||||
assert s.pop() == 20
|
||||
assert s.pop() == 10
|
||||
assert s.is_empty() is True
|
||||
|
||||
try:
|
||||
s.pop()
|
||||
assert False
|
||||
except EmptyError:
|
||||
pass
|
||||
|
||||
try:
|
||||
s.peek()
|
||||
assert False
|
||||
except EmptyError:
|
||||
pass
|
||||
|
||||
print("All Stack tests passed.") #only runs if all previous tests pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user