-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlab_stack.py
More file actions
45 lines (40 loc) · 1.43 KB
/
lab_stack.py
File metadata and controls
45 lines (40 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Stack:
class Full(Exception):
pass
class Empty(Exception):
pass
def __init__( self, maxSize ):
""" Initialise the stack, maxSize is the maximum number of
values that can be stored in the stack at any time """
self.__maxSize = maxSize
self.__stack = [None]*self.__maxSize
self.__pos = 0
def push( self, value ):
""" Add value to the top of the stack, raises Stack.Full
exception is stack is full """
if self.num_items() < self.__maxSize:
self.__stack[self.__pos] = value
self.__pos += 1
else:
raise self.Full( 'Can\'t push ' + str(value) )
def num_items( self ):
""" Returns the number of values currently stored in the
stack """
return self.__pos
def top( self ):
""" Returns the value currently stored at the top of the
stack, raises Stack.Empty exception is stack is
empty """
if self.num_items() > 0:
return self.__stack[self.__pos]
else:
raise self.Empty()
def pop( self ):
""" Removes and returns the value currently stored at the
top of the stack, raises Stack.Empty exception is stack
is empty """
if self.num_items() > 0:
self.__pos -= 1
return self.__stack[self.__pos]
else:
raise self.Empty()