Stacks
Basic Data Structures Stacks Brad Miller
David Ranum
1/25/06
Basic Data Structures
Stacks
Outline
1
Stacks What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Outline
1
Stacks What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
A Stack of Books
Python Calculus Physics Music History
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
A Stack of Primitive Python Objects
8.4
Top
True “dog" 4 Base
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
The Reversal Property of Stacks
8.4 True
first
last "dog"
8.4
True
"dog" 4
first
4
last
Original Order
4
"dog"
True
Reversed Order
Basic Data Structures
8.
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Outline
1
Stacks What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Stack() creates a new stack that is empty. It needs no parameters and returns an empty stack. push(item) adds a new item to the top of the stack. It needs the item and returns nothing. pop() removes the top item from the stack. It needs no parameters and returns the item. The stack is modified. peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified. isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value. size() returns the number of items on the stack. It needs no parameters and returns an integer. Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Outline
1
Stacks What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Stack Implementation in Python I 1 2 3
c l a s s Stack: d e f __init__(self): self.items = []
4 5 6
d e f isEmpty(self): r e t u r n self.items == []
7 8 9
d e f push(self, item): self.items.append(item)
10 11 12
d e f pop(self): r e t u r n self.items.pop()
13 14
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Stack Implementation in Python II
15 16
d e f peek(self): r e t u r n self.items[len(self.items)-1]
17 18 19
d e f size(self): r e t u r n len(self.items)
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Alternative ADT Stack Implementation in Python I 1 2 3
c l a s s Stack: d e f __init__(self): self.items = []
4 5 6
d e f isEmpty(self): r e t u r n self.items == []
7 8 9
d e f push(self, item): self.items.insert(0,item)
10 11 12
d e f pop(self): r e t u r n self.items.pop(0)
13 14
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Alternative ADT Stack Implementation in Python II
15 16
d e f peek(self): r e t u r n self.items[0]
17 18 19
d e f size(self): r e t u r n len(self.items)
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Outline
1
Stacks What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Basic Data Structures
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Stacks
Matching Parentheses
Most recent open matches first close (
(
)
(
(
)
)
(
First open may wait until last close
Basic Data Structures
)
)
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Simple Balanced Parentheses I 1 2
d e f parChecker(symbolString): s = Stack()
3 4 5
balanced = True index = 0
6 7 8 9 10 11
w h i l e index < len(symbolString) and balanced: symbol = symbolString[index] i f symbol == "(": s.push(symbol) else:
12 13 14
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Simple Balanced Parentheses II 15 16 17 18
i f s.isEmpty(): balanced = False else: s.pop()
19 20
index = index + 1
21 22 23 24 25
i f balanced and s.isEmpty(): r e t u r n True else: r e t u r n False
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Outline
1
Stacks What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Balanced Symbols–A General Case I 1
d e f parChecker(symbolString):
2 3
s = Stack()
4 5 6
balanced = True index = 0
7 8 9 10 11 12
w h i l e index < len(symbolString) and balanced: symbol = symbolString[index] i f symbol i n "([{": s.push(symbol) else:
13 14
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Balanced Symbols–A General Case II 15 16 17 18 19 20 21
i f s.isEmpty(): balanced = False else: top = s.pop() i f n o t matches(top,symbol): balanced = False
22 23
index = index + 1
24 25 26 27 28
i f balanced and s.isEmpty(): r e t u r n True else: r e t u r n False
29
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Balanced Symbols–A General Case III
30 31 32
d e f matches(open,close): opens = "([{" closers = ")]}"
33 34
r e t u r n opens.index(open) == closers.index(close)
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Outline
1
Stacks What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Basic Data Structures
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Stacks
Decimal-to-Binary Conversion
1 rem = 1
1 rem = 0
58 / 2 = 29
rem = 0
29 / 2 = 14
rem = 1
14 / 2 = 7
rem = 0
7/2=3
rem = 1
3/2=1
Basic Data Structures
0 1 0 0
rem = 1
1/ 2 = 0
1
rem = 1
1
pop remainders
116 / 2 = 58
push remainders
233 / 2 = 116
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Decimal to Binary Conversion 1
d e f divideBy2(decNumber):
2 3
remstack = Stack()
4 5 6 7 8
w h i l e decNumber > 0: rem = decNumber % 2 remstack.push(rem) decNumber = decNumber / 2
9 10 11 12
binString = "" w h i l e n o t remstack.isEmpty(): binString = binString + str(remstack.pop())
13 14
r e t u r n binString Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Conversion to Any Base I 1
d e f baseConverter(decNumber,base):
2 3
digits = "0123456789ABCDEF"
4 5
remstack = Stack()
6 7 8 9 10
w h i l e decNumber > 0: rem = decNumber % base remstack.push(rem) decNumber = decNumber / base
11 12 13 14
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Conversion to Any Base II
15 16 17
newString = "" w h i l e n o t remstack.isEmpty(): newString = newString + digits[remstack.pop()]
18 19
r e t u r n newString
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Outline
1
Stacks What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Basic Data Structures
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Stacks
Moving Operators to the Right for Postfix Notation
(
A
+
(
B
*
C
Basic Data Structures
)
)
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Stacks
Moving Operators to the Left for Prefix Notation
(
A
+
(
B
*
C
Basic Data Structures
)
)
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Converting a Complex Expression to Prefix and Postfix Notations
(A + B) * C - (D - E) * (F + G)
(((A + B) * C) - ((D - E) * (F + G))) Prefix -*+A B C *- D E + F G
Postfix A B + C * D E - F G + * -
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
1
Create an empty stack called opstack for keeping operators. Create an empty list for output.
2
Convert the input infix string to a list by using the string method split.
Basic Data Structures
Stacks
3
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Scan the token list from left to right. If the token is an operand, append it to the end of the output list. If the token is a left parenthesis, push it on the opstack. If the token is a right parenthesis, pop the opstack until the corresponding left parenthesis is removed. Append each operator to the end of the output list. If the token is an operator, *, /, +, or -, push it on the opstack. However, first remove any operators already on the opstack that have higher or equal precedence and append them to the output list.
4
When the input expression has been completely processed, check the opstack. Any operators still on the stack can be removed and appended to the end of the output list. Basic Data Structures
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Stacks
Converting A * B + C * D to Postfix Notation A*B+C*D A
A
*
B
+
*
*
*
B
C
*
D
*
*
*
+
+
+
+
+
*
C
D
AB*CD*+
Basic Data Structures
+
*
+
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Converting Infix Expressions to Postfix Expressions I 1 2
import string d e f infixToPostfix(infixexpr):
3 4 5 6 7 8 9
prec = {} prec["*"] prec["/"] prec["+"] prec["-"] prec["("]
= = = = =
3 3 2 2 1
10 11 12
opStack = Stack() postfixList = []
13 14
tokenList = infixexpr.split() Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Converting Infix Expressions to Postfix Expressions II 15 16 17 18 19 20 21 22 23 24 25
f o r token i n tokenList: i f token i n string.uppercase: postfixList.append(token) e l i f token == ’(’: opStack.push(token) e l i f token == ’)’: topToken = opStack.pop() w h i l e topToken != ’(’: postfixList.append(topToken) topToken = opStack.pop()
26 27 28 29
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Converting Infix Expressions to Postfix Expressions III 30 31 32 33
else: w h i l e ( n o t opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop())
34 35
opStack.push(token)
36 37 38
w h i l e n o t opStack.isEmpty(): postfixList.append(opStack.pop())
39 40
r e t u r n string.join(postfixList)
Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Stack Contents During Evaluation Left to Right Evaluation 4
push
5
6
*
push
push
pop twice and do math pop twice and do math
6
4
+
5
5
30
4
4
4
Basic Data Structures
34
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
A More Complex Example of Evaluation 7
8
+
3
2
+
/
2 8 7
7
15
3
3
5
15
15
15
Basic Data Structures
3
Stacks
1 2
3
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Create an empty stack called operandStack. Convert the string to a list by using the string method split. Scan the token list from left to right. If the token is an operand, convert it from a string to an integer and push the value onto the operandStack. If the token is an operator, *, /, +, or -, it will need two operands. Pop the operandStack twice. The first pop is the second operand and the second pop is the first operand. Perform the arithmetic operation. Push the result back on the operandStack.
4
When the input expression has been completely processed, the result is on the stack. Pop the operandStack and return the value. Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Postfix Evaluation I 1 2 3
d e f postfixEval(postfixExpr): operandStack = Stack() tokenList = postfixExpr.split()
4 5 6 7 8 9 10 11 12
f o r token i n tokenList: i f token i n "0123456789": operandStack.push(int(token)) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token,operand1,operand2) operandStack.push(result)
13 14
r e t u r n operandStack.pop() Basic Data Structures
Stacks
What is a Stack? The Stack Abstract Data Type Implementing a Stack in Python Simple Balanced Parentheses Balanced Symbols (A General Case) Converting Decimal Numbers to Binary Numbers Infix, Prefix and Postfix Expressions
Postfix Evaluation II 15 16 17 18 19 20 21 22 23 24 25 26
d e f doMath(op, op1, op2): i f op == "*": r e t u r n op1 * op2 else: i f op == "/": r e t u r n op1 / op2 else: i f op == "+": r e t u r n op1 + op2 else: r e t u r n op1 - op2
Basic Data Structures