-
Notifications
You must be signed in to change notification settings - Fork 0
/
arraystack.py
78 lines (51 loc) · 1.94 KB
/
arraystack.py
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
68
69
70
71
72
73
74
75
76
77
#-----------------------------------------------------------------------
# arraystack.py
#-----------------------------------------------------------------------
import stdlib.stdio as stdio
# A Stack object is a last-in-first-out collection.
class Stack:
#-------------------------------------------------------------------
# Construct an empty Stack object.
def __init__(self):
self._a = [] # Items
#-------------------------------------------------------------------
# Return True if self is empty, and False otherwise.
def isEmpty(self):
return len(self._a) == 0
#-------------------------------------------------------------------
# Push object item onto the top of self.
def push(self, item):
self._a += [item]
#-------------------------------------------------------------------
# Pop the top object from self and return it.
def pop(self):
return self._a.pop()
#-------------------------------------------------------------------
# Return a string representation self.
def __str__(self):
s = ''
for item in self._a:
s = str(item) + ' ' + s
#for item in reversed(self._a):
# s += str(item) + ' '
return s
#-----------------------------------------------------------------------
# Test the Stack class by reading strings from standard input and
# pushing or popping as indicated. A minus sign indicates pop (and
# write to standard output), and any other string indicates push.
def main():
stack = Stack()
while not stdio.isEmpty():
item = stdio.readString()
if item != '-':
stack.push(item)
else:
stdio.write(stack.pop() + ' ')
stdio.writeln()
if __name__ == '__main__':
main()
#-----------------------------------------------------------------------
# more tobe.txt
# to be or not to - be - - that - - - is
#
# to be not that or be