Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

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 hours: TR 1-2pm or by appointment. Office location: CI2046. Email: simmondsd[@]uncw.edu

2 CSC 231 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

3 CSC 231 3

4 CSC 231 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

5 CSC 231 Creating Lists 5 list1 = list() # Create an empty list list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4 list3 = list(["red", "green", "blue"]) # Create a list with strings list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5 list5 = 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:

6 CSC 231 list Methods 6

7 CSC 231 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

8 CSC 231 … 8

9 CSC 231 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

10 CSC 231 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 = {s 1 s 2 s 3 … s N } ▫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

11 CSC 231 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

12 CSC 231 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

13 CSC 231 Pushing 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 17239744 0 1 2 3 4 5 6 7 8 9 stk:

14 CSC 231 After 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 17239744 0 1 2 3 4 5 6 7 8 9 stk:

15 CSC 231 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 9 stk: topStk2 = 6 17239744 49573 0 1 2 3 4 5 6 7 8 9 stks: topStk1 = 2

16 CSC 231 A Stack class 16 # Implementation of a stack ADT class 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()

17 CSC 231 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

18 CSC 231 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

19 CSC 231 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

20 CSC 231 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

21 CSC 231 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

22 CSC 231 Decimal to Binary Number Conversion In Fundamentals of Python: From First Programs Through Data Structures 22

23 CSC 231 Evaluating 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

24 CSC 231 Evaluating 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

25 CSC 231 Evaluating Arithmetic Expressions Fundamentals of Python: From First Programs Through Data Structures 25 Arithmetic Expressions INFIXPREFIXPOSTFIX A+B+ABAB+ A+B*C+A*BCABC*+ (A+B)*C*+ABCAB+C* A+B*C+D (A+B)*C+D (A+B)*(C+D) A*B+C*D A+B+C+D (A+B)*C-(D-E)*(F+G)

26 CSC 231 Algorithm for postfix Evaluating 1.Create an empty stack 2.Convert the postfix expression to a list using split 3.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

27 CSC 231 Evaluating Arithmetic Expressions 6undamentals of Python: 6rom 6irst Programs Through 2ata Structures 27 3rithmetic Expressions INFIXPOSTFIX 3+434+ 3+4*5345*+ (3+4)*534+5* 3+4*5+2345*+2+ (3+4)*5+234+5*2+ (3+4)*(5+2)34+52+* 3*4+5*234*52*+ 3+4+5+234+5+2+ (3+4)*5-(9-6)*(6+7) 34+5*96-67+*-

28 CSC 231 Pre 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

29 CSC 231 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

30 CSC 231 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

31 CSC 231 31 ______________________ Devon M. Simmonds Computer Science Department University of North Carolina Wilmington _____________________________________________________________ Qu es ti ons? Reading for next class?

32 CSC 231 Pre 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

33 CSC 231 Evaluating Arithmetic Expressions Fundamentals of Python: From First Programs Through Data Structures 33 Arithmetic Expressions INFIXPREFIXPOSTFIX A+B+ABAB+ A+B*C+A*BCABC*+ (A+B)*C*+ABCAB+C* A+B*C+D++A*BCDABCD*++ (A+B)*C+D+*+ABCDAB+C*D+ (A+B)*(C+D)*+AB+CDAB+CD+* A*B+C*D+*AB*CDAB*CD*+ A+B+C+D+++ABCDAB+C+D+ (A+B)*C-(D-E)*(F+G) -*+ABC*-DE+FGAB+C*DE-FG+*-

34 CSC 231 Algorithm for postfix Evaluating 1.Create an empty stack 2.Convert the postfix expression to a list 3.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


Download ppt "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."

Similar presentations


Ads by Google