Top Banner
CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office hours: TR 1-2pm or by appointment. Office location: CI2046. Email: simmondsd[@]uncw.edu
34

CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

Jan 21, 2016

Download

Documents

Elmer Hopkins
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Stacks

1

Devon M. SimmondsUniversity of North Carolina, Wilmington

TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office hours: TR 1-2pm or by appointment. Office location: CI2046. Email: simmondsd[@]uncw.edu

Page 2: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Objectives

2

Describe the stack ADT Understand pre and post

conditions for stack operations. Apply the stack ADT to real

world applications. Explain how the Python virtual

machine uses a stack to support function and method calls

Page 3: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC2313

Summary of Lists

Page 4: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Lists• A list is an ordered collection of zero or more

references to Python data objects. • Lists are written as comma-delimited values

enclosed in square brackets. • The empty list is simply [ ].

4

Page 5: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC2315

Creating Lists

list1 = list() # Create an empty listlist2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4list3 = list(["red", "green", "blue"]) # Create a list with stringslist4 = list(range(3, 6)) # Create a list with elements 3, 4, 5list5 = list("abcd") # Create a list with characters a, b, c

list1 = [] # Same as list()list2 = [2, 3, 4] # Same as list([2, 3, 4]) list3 = ["red", "green"] # Same as list(["red", "green"])

Creating list using the list class

For convenience, you may create a list using the following syntax:

Page 6: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC2316

list Methods

list

append(x: object): None

insert(index: int, x: object): None

remove(x: object): None

index(x: object): int

count(x: object): int

sort(): None

reverse(): None

extend(l: list): None

pop([i]): object

Add an item x to the end of the list.

Insert an item x at a given index. Note that the first element in the list has index 0.

Remove the first occurrence of the item x from the list.

Return the index of the item x in the list.

Return the number of times item x appears in the list.

Sort the items in the list.

Reverse the items in the list.

Append all the items in L to the list.

Remove the item at the given position and return it. The square bracket denotes that parameter is optional. If no index is specified, list.pop() removes and returns the last item in the list.

Page 7: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Typical Operations on Lists• Finding length of list• Finding the smallest value• Finding the largest value• Summing the elements in the list• Slicing a list• Sorting a list• Testing membership• List comprehension• Splitting a string into a list

7

Page 8: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

• …

8

Stacks – a last in first out data

structure.

Page 9: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Abstract Data Types (ADTs)

•An ADT is the specification of:▫A set of objects (data) and▫A set of operations performed on the

objects

•ADT is specified without regard to:▫Programming language▫Implementation nuances

9

Page 10: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Stacks

• A stack is a linear list in which items are added and removed from one end of the list called its top.

• The Stack ADT (LIFO)▫ Stack S = {s1 s2 s3 … sN}

▫ Operations: push(item) - adds a new item to the stack. pop():item - removes and return item at the top of the stack. peek ():item- returns item at top of stack, stack unchanged.

Peek is sometine called top isEmpty() – returns True when the stack is empty. size() - returns the number of items on the stack.

10

Page 11: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Overview of Stacks

•Stack: LIFO structure in which access is completely restricted to just one end, called the top▫Basic operations: push and pop

from Fundamentals of Python: From First Programs Through Data Structures

11

Page 12: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

List/Array implementation of stacks

• A stack type is not built into Python• To implement a stack, items are inserted and

removed at the same end (called the top)• Efficient list implementation requires that the top of

the stack be towards the center of the array, not fixed at one end

• To use a list to implement a stack, you need both the array itself and an integer

• The integer tells you either:▫Which location is currently the top of the stack, or▫How many elements are in the stack

12

Page 13: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Pushing and popping

• If the bottom of the stack is at location 0, then an empty stack is represented by top = -1 or count = 0

• To add (push) an element, either:▫ Increment top and store the element in stk[top]], or▫ Store the element in stk[count]] and increment count

• To remove (pop) an element, either:▫ Get the element from stk[top]] and decrement top, or▫ Decrement count and get the element in stk[count]]

13

top = 3 or count = 4

17 23 97 44

0 1 2 3 4 5 6 7 8 9stk:

Page 14: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231After popping

• When you pop an element, do you just leave the “deleted” element sitting in the array?

• The surprising answer is, “it depends”▫ If this is an array of primitives, or if you are programming in

C or C++, then doing anything more is just a waste of time▫ If you are programming in Java, and the array contains

objects, you should set the “deleted” array element to null▫ Why? To allow it to be garbage collected!

14

top = 2 or count = 3

17 23 97 44

0 1 2 3 4 5 6 7 8 9stk:

Page 15: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Sharing space• Of course, the bottom of the stack could be at

the other end

• Sometimes this is done to allow two stacks to share the same storage area

15

top = 6 or count = 4

17239744

0 1 2 3 4 5 6 7 8 9stk:

topStk2 = 6

1723974449 57 3

0 1 2 3 4 5 6 7 8 9stks:

topStk1 = 2

Page 16: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

A Stack class

16

# Implementation of a stack ADTclass Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop()

def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items)

def getStack(self): return self.items

def main(): s = Stack() print(s.is_empty()) for n in range(7): s.push(n*10) print(s.getStack())

main()

Page 17: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Instantiating a Stack

•We assume that any stack class that implements this interface will also have a constructor that allows its user to create a new stack instance

•This is how we instantiate a stack: s = Stack()

Fundamentals of Python: From First Programs Through

Data Structures

17

Page 18: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Applications of Stacks

•We now discuss other applications of stacks:▫Matching parentheses▫Converting decimal numbers to binary

numbers▫Evaluating arithmetic expressions▫Using stacks to solve backtracking

problems▫Using stacks in computer memory

management

Fundamentals of Python: From First Programs Through

Data Structures

18

Page 19: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Example Application: Matching Parentheses•Compilers need to determine if the

bracketing symbols in expressions are balanced correctly

Fundamentals of Python: From First Programs Through Data Structures

19

Page 20: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Example Application: Matching Parentheses (continued)• Approach 1: Count left and right parentheses

▫Does not work• Approach 2:

▫Scan expression; push left brackets onto a stack▫On encountering a closing bracket, if stack is

empty or if item on top of stack is not an opening bracket of the same type, we know the brackets do not balance

▫Pop an item off the top of the stack and, if it is the right type, continue scanning the expression

▫When we reach the end of the expression, stack should be empty; if not, brackets do not balance

Fundamentals of Python: From First Programs Through

Data Structures

20

Page 21: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Decimal to Binary Number Conversion

•Algorithm▫Repeat until number is < 2

Divide number by 2 (modular arithmetic) Place remainder on stack Number becomes number mod 2

▫Push number on the stack▫Pop elements from stack and arrange so

that the last element on the stack is the first digit of the binary number

Fundamentals of Python: From First Programs Through Data Structures

21

Page 22: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Decimal to Binary Number Conversion

•In

Fundamentals of Python: From First Programs Through Data Structures

22

Page 23: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Evaluating Arithmetic Expressions•In the infix form of an arithmetic

expression, each operator is located between its operands

•In the prefix form of an arithmetic expression, each operator comes immediately before its operands

•In the postfix form of an arithmetic expression, an operator immediately follows its operands

Fundamentals of Python: From First Programs Through Data Structures

23

Page 24: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Evaluating Arithmetic Expressions• infix form of an arithmetic expression

▫A + B•prefix form of an arithmetic expression

▫+AB•postfix form of an arithmetic expression

▫AB+

Fundamentals of Python: From First Programs Through Data Structures

24

Page 25: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Evaluating Arithmetic Expressions

Fundamentals of Python: From First Programs Through Data Structures

25

Arithmetic ExpressionsINFIX PREFIX POSTFIXA+B +AB AB+

A+B*C +A*BC ABC*+(A+B)*C *+ABC AB+C*

A+B*C+D(A+B)*C+D

(A+B)*(C+D)A*B+C*DA+B+C+D

(A+B)*C-(D-E)*(F+G)

Page 26: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Algorithm for postfix Evaluating

1. Create an empty stack2. Convert the postfix expression to a list using split3. Scan the token list from left to right

a. If the token is an operand, convert it from a string to an integer and push the value onto the stack.

b. If the token is an operator, *, ?, +, -, it needs two operands. Pop the stack twice. The first pop produces the second operand and the second pop produces the first operand.

c. Perform the arithmetic operation and push the result back on the stack.

4. When the list is empty, and the expression has been completely processed, the result is on the stack. Pop the stack and return the result.

Fundamentals of Python: From First Programs Through Data Structures

26

Page 27: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Evaluating Arithmetic Expressions

6undamentals of Python: 6rom 6irst Programs Through 2ata Structures

27

3rithmetic ExpressionsINFIX POSTFIX

3+4 34+3+4*5 345*+

(3+4)*5 34+5*3+4*5+2 345*+2+

(3+4)*5+2 34+5*2+(3+4)*(5+2) 34+52+*

3*4+5*2 34*52*+3+4+5+2 34+5+2+

(3+4)*5-(9-6)*(6+7) 34+5*96-67+*-

Page 28: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Pre and Post Conditions for Stack Operations

• Precondition – a condition that must be true before the operation executes.

• Postcondition – a condition that must be true after the operation executes.

• The Stack ADT (LIFO)▫ push(item) - add a new item to the stack.

Pre: Post:

▫ pop(item) - remove and return last item added. Pre: Post:

▫ peek ()- remove and return last item added. Pre: Post:

▫ isEmpty() - checks whether the stack is empty. Pre: Post:

▫ size() - returns the number of items on the stack. Pre: Post:

28

Page 29: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Error checking• There are two stack errors that can occur:

▫ Underflow: trying to pop (or peek at) an empty stack

▫ Overflow: trying to push onto an already full stack• For underflow, you should throw an exception• If you don’t catch it yourself, an

“OutOfBound” exception my be thrown.• You could create your own, more informative

exception• For overflow, you could do the same things• Or, you could check for the problem, and copy

everything into a new, larger array

29

Page 30: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Summary

30

Describe the stack ADT Understand pre and post conditions

for stack operations. Apply the stack ADT to real world

applications. Balancing parentheses Decimal to binary conversion

Explain how the Python virtual machine uses a stack to support function and method calls

Page 31: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC23131

______________________Devon M. Simmonds

Computer Science Department

University of North Carolina Wilmington

_____________________________________________________________

Qu es ti ons?

Reading for next class?

Page 32: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Pre and Post Conditions for Stack Operations

• Precondition – a condition that must be true before the operation executes.• Postcondition – a condition that must be true after the operation executes.• The Stack ADT (LIFO)

▫ push(item) - adds a new item to the stack. Pre: Stack is not full Post: item is at the top of the stack

▫ pop() - removes and return item at the top of the stack. Pre: stack is not empty Post: size()@pre – 1 == size()@post and peek()@pre == item removed

▫ peek ()- returns item at the top of the stack. Stack is unchanged. Pre: None Post: Stack unchanged

▫ isEmpty() – returns True when the stack is empty. Pre: None Post: Stack unchanged

▫ size() - returns the number of items on the stack. Pre: None Post: result = # of items@pre, stack unchanged

32

Page 33: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231Evaluating Arithmetic Expressions

Fundamentals of Python: From First Programs Through Data Structures

33

Arithmetic ExpressionsINFIX PREFIX POSTFIXA+B +AB AB+

A+B*C +A*BC ABC*+(A+B)*C *+ABC AB+C*

A+B*C+D ++A*BCD ABCD*++(A+B)*C+D +*+ABCD AB+C*D+

(A+B)*(C+D) *+AB+CD AB+CD+*A*B+C*D +*AB*CD AB*CD*+A+B+C+D +++ABCD AB+C+D+

(A+B)*C-(D-E)*(F+G) -*+ABC*-DE+FG AB+C*DE-FG+*-

Page 34: CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

CSC231

Algorithm for postfix Evaluating

1. Create an empty stack2. Convert the postfix expression to a list3. Scan the token list from left to right

a. If the token is an operand, convert it from a string to an integer and push the value onto the stack.

b. If the token is an operator, *, ?, +, -, it needs two operands. Pop the stack twice. The first pop produces the second operand and the second pop produces the first operand.

c. Perform the arithmetic operation and push the result back on the stack.

4. When the list is empty, and the expression has been completely processed, the result is on the stack. Pop the stack and return the result.

Fundamentals of Python: From First Programs Through Data Structures

34