-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstack_simulator.py
More file actions
69 lines (54 loc) · 1.71 KB
/
stack_simulator.py
File metadata and controls
69 lines (54 loc) · 1.71 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# file stack.py
# utility for "stack:
# initialization is done above.
# stack.py
StackError = 'StackError'
class Stack:
"""A generic Stack class."""
def __init__(self, something=None):
if type(something) == type([]):
self._data = []
for item in something:
self._data.append(item)
elif isinstance(something, Stack):
# copy constructor
self._data = []
for x in something._data:
self._data.append(x)
elif something is None:
self._data = []
else:
self._data = []
self._data.append(something)
def push(self, obj):
"""Push an element on the Stack."""
self._data.append(obj)
def pop(self):
"""Pop an element from the Stack."""
if len(self._data) > 0:
result = self._data[-1] # get the last (topmost) element
del self._data[-1]
return result
else:
raise StackError, "Stack is empty"
def pushmore(self, seq):
for item in seq: self.push(item)
def popmore(self, number):
seq = []
for x in number: seq.append(self.pop())
return seq
def isempty(self):
return len(self._data) == 0
def num_items(self):
return len(self._data)
def __repr__(self):
"""Representation of a Stack."""
return `self._data`
# I'll take a list for this until I have something better
def __len__(self):
return len(self._data)
# __add__ (+) is a replacement for push, nothing more, nothing less
def __add__(self, obj):
somestack = Stack(self)
somestack.push(obj)
return somestack