forked from ninas/umonya_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstacks.html
178 lines (142 loc) · 6.71 KB
/
stacks.html
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Introductory Programming in Python: Advanced Data Structures: Stacks</title>
<link rel='stylesheet' type='text/css' href='style.css' />
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script src="animation.js" type="text/javascript">
</script>
</head>
<body onload="animate_loop()">
<div class="page">
<h1>Introductory Programming in Python: Lesson 30<br />
Advanced Data Structures: Stacks</h1>
<div class="centered">
[<a href="queues.html">Prev: Advanced Data Structures: Queues</a>] [<a href="index.html">Course Outline</a>] [<a href="trees.html">Next: Advanced Data Structures: Trees</a>]
</div>
<h2>Last In, First Out</h2>
<p>A stack is an order collection of objects which can only be operated
on in two ways. We can add an object to the end of the collection,
known as <strong>pushing an object onto the stack</strong>, or we can
remove the last item on the stack, known as <strong>popping the
stack</strong>. We can only inspect the last item on the stack too. The
rest of the collection is hidden from us, strictly speaking, although
this depends greatly on the implementation of the stack. The airport
luggage example illustrates the working of a stack. The first person to
check their baggage in finds that their baggage is the last available
at the other end on the conveyor belt. Sometimes being late does pay
off. In fact the baggage will come out in the reverse order it was put
in.</p>
<p>Stacks are one of those tools in every programmer's toolkit. Which
is not to say they can solve every problem, but they are found in a
surprising variety of solutions. The key concept to understand about a
stack is that they are good for reordering things in a variety of ways,
not just for reversing things. They are also good a 'remembering
things' so they can be undone, hence the term 'undo stack'.</p>
<h2>Lists as Stacks</h2>
<p>Python offers us a convenient set of methods to operate lists as
stacks.</p>
<ul>
<li><strong>Inspection</strong>: The simplest method in python for
inspecting the value on the top of the stack, is to index the -1th
element, as in <code><list>[-1]</code>.</li>
<li><strong>Pushing</strong>: Fortunately the append method serves
admirably the function of a stack push.</li>
<li><strong>Popping</strong>: And python provides us with a list
method conveniently named 'pop', <code><list>.pop()</code>,
that removes the last value from the list and returns it.</li>
</ul>
<pre class='listing'>
Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [MSC v.1310 32 bit (Intel)] on win32
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> stack = []
>>> stack.append(3)
>>> stack
[3]
>>> stack.append(2)
>>> stack
[3, 2]
>>> stack.append(1)
>>> stack
[3, 2, 1]
>>> stack.pop()
1
>>> stack.pop()
2
>>> stack.pop()
3
>>>
</pre>
<h2>Infix to Postfix Conversion: A Worked Example</h2>
<p>There are various ways to write down an arithmetic expression. We
are used to a method know as infix notation, called such because
operator's are written in between operands. Infix notation suffers a
severe drawback, in that the precedence of operators is implicit and
changes the order of evaluation. Consider the expression '4*(2+3)'. We
cannot simply evaluate this expression from left to right. We want to
change the order in which it is evaluated to match the order of
precedence. Order changing, sounds like a job for soooperr-stack!</p>
<p>The other two notations are called prefix and postfix notation
respectively. Prefix notation lists operators prior to their operands,
whilst postfix lists operators after their respective operands. We
would write the former expression as '*4+23' or '423+*' in prefix and
postfix notation respectively. Although basically equivalent except for
order, computer science has settled on postfix as a preferred method
for evaluating expressions. Note that the precedence of the operators in
in the post- and pre-fix notations does not need brackets to define a
change in precedence. We can evaluate these expressions from left to
right, as such in the case of prefix notation</p>
<ol>
<li>* indicates we must multiply the next two operands, and replace
them and the operator with the resulting value</li>
<li>4 is the first operand</li>
<li>+ indicates we must add the next two operands and replace the
operator and it's operands with the resulting value</li>
<li>2 is the first operand of the plus</li>
<li>3 is the second operand of the plus</li>
<li>2+3 = 5, so we replace the +23 part with 5 yielding '*45'</li>
<li>5 is the second operand of the multiply</li>
<li>4*5 = 10, so we replace the *45 part with 20 yielding '20'
which requires no further evaluation, as there are no more
operators.</li>
</ol>
<p>Since it is trivial to evaluate a postfix (or prefix) expression, we
want to write a function that converts an infix expression to a postfix
one. For the sake of example, we shall only allow single digit numbers,
and the binary operators '+', '-', '*', '/', and parentheses.</p>
<pre class='listing'>
def postfix(infix):
operator_stack = []
output_queue = ''
for c in infix:
if c.isdigit():
output_queue += c
elif c in ['+', '-', '*', '/']:
while len(operator_stack) > 0
and operator_stack[len(operator_stack)-1] in ['*', '/']
and c in ['+', '-']:
output_queue += operator_stack.pop()
operator_stack.append(c)
elif c == '(':
operator_stack.append(c)
elif c == ')':
o = operator_stack.pop()
while o != '(':
output_queue += o
o = operator_stack.pop()
while len(operator_stack) > 0:
output_queue += operator_stack.pop()
return output_queue
</pre>
<h2>Exercises</h2>
<div class="centered">
[<a href="queues.html">Prev: Advanced Data Structures: Queues</a>] [<a href="index.html">Course Outline</a>] [<a href="trees.html">Next: Advanced Data Structures: Trees</a>]
</div>
</div>
<div class="pagefooter">
Copyright © James Dominy 2007-2008; Released under the <a href="http://www.gnu.org/copyleft/fdl.html">GNU Free Documentation License</a><br />
<a href="intropython.tar.gz">Download the tarball</a>
</div>
</body>
</html>