Lecture 8: Simple Calculator Application

Similar documents
Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017

March 13/2003 Jayakanth Srinivasan,

Stacks. Revised based on textbook author s notes.

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

Stacks and their Applications

Parsing Scheme (+ (* 2 3) 1) * 1

CS 211. Project 5 Infix Expression Evaluation

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Lecture 12 ADTs and Stacks

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

CS 206 Introduction to Computer Science II

Lecture 2: Python Arithmetic

Lecture 18: Lists II. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS THE STACK

CS 211 Programming Practicum Spring 2018

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

Lecture 8: ADT List. CS2504/CS4092 Algorithms and Linear Data Structures. Dr Kieran T. Herley. Department of Computer Science University College Cork

CS 211 Programming Practicum Spring 2017

Formal Languages and Automata Theory, SS Project (due Week 14)

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

Infix to Postfix Conversion

Review: Expressions, Variables, Loops, and more.

Linear Data Structure

CSE P 501 Exam 8/5/04

Lecture 10: Boolean Expressions

BBM 201 DATA STRUCTURES

BBM 201 DATA STRUCTURES

Lecture 4 Stack and Queue

Syntax-Directed Translation. Lecture 14

Programming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras

CS 211 Programming Practicum Fall 2018

Simple Lexical Analyzer

Algorithms and Data Structures

Stacks Calculator Application. Alexandra Stefan

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College

Jython. secondary. memory

The Stack and Queue Types

SimpleCalc. which can be entered into a TI calculator, like the one on the right, like this:

[CS302-Data Structures] Homework 2: Stacks

Outline. Stacks. 1 Chapter 5: Stacks and Queues. favicon. CSI33 Data Structures

Expressions and Assignment

Data Structures and Algorithms

STACKS AND QUEUES. Problem Solving with Computers-II

CSE P 501 Exam 8/5/04 Sample Solution. 1. (10 points) Write a regular expression or regular expressions that generate the following sets of strings.

Arithmetic Operators. Portability: Printing Numbers

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

PA3 Design Specification

Problem with Scanning an Infix Expression

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Data Structures Week #3. Stacks

An Introduction to Trees

Semantic analysis and intermediate representations. Which methods / formalisms are used in the various phases during the analysis?

Postfix Notation is a notation in which the operator follows its operands in the expression (e.g ).

CS 206 Introduction to Computer Science II

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

ASTS, GRAMMARS, PARSING, TREE TRAVERSALS. Lecture 14 CS2110 Fall 2018

syntax tree - * * * * * *

Lecture 2: Writing Your Own Class Definition

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

A Simple Syntax-Directed Translator

CS W3134: Data Structures in Java

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Stack Abstract Data Type

Variable and Data Type I

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Lecture Data Structure Stack

Project 1: Implementation of the Stack ADT and Its Application

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

CS2383 Programming Assignment 3

Lecture 10: Strings. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture P5: Abstract Data Types

Chapter 04: Instruction Sets and the Processor organizations. Lesson 18: Stack-based processor Organisation

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

Variable and Data Type I

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

1. Stack Implementation Using 1D Array

Context-Free Grammar. Concepts Introduced in Chapter 2. Parse Trees. Example Grammar and Derivation

ADTS, GRAMMARS, PARSING, TREE TRAVERSALS

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

Lecture 4: Simple Input-Calculate-Output Programs

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking

Topics Power tends to corrupt; absolute power corrupts absolutely. Computer Organization CS Data Representation

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

ARM Cortex A9. ARM Cortex A9

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

The CPU and Memory. How does a computer work? How does a computer interact with data? How are instructions performed? Recall schematic diagram:

#06 More Structures LIFO FIFO. Contents. Queue vs. Stack 3. Stack Operations. Pop. Push. Stack Queue Hash table

Functional Programming. Pure Functional Programming

Structure and Interpretation of Computer Programs

Lecture 8: Context Free Grammars

Transcription:

Lecture 8: Simple Calculator Application Postfix Calculator Dr Kieran T. Herley Department of Computer Science University College Cork 2016/17 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 1 / 15

Summary Postfix Calculator KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 2 / 15

Postfix notation Postfix is a notation of writing arithmetic expressions in which operands appear after the operands to which they apply. Examples: 1 2 + 3 3 4 12 1 2 + 3 + 6 1 2 3 + + 6 1 2 3 + 7 Advantages: As expressive as traditional infix notation Simple to evaluate using simple stack-based algorithm KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 3 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise Illustration op. push(17) 17 stack (top to right) empty KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise Illustration op. push(17) 17 push(23) 17 23 stack (top to right) empty KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise Illustration op. push(17) 17 push(23) 17 23 stack (top to right) empty pop() 17 returns 23 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise Illustration op. push(17) 17 push(23) 17 23 stack (top to right) empty pop() 17 returns 23 push(29) 17 29 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise Illustration op. push(17) 17 push(23) 17 23 stack (top to right) empty pop() 17 returns 23 push(29) 17 29 push(31) 17 29 31 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise Illustration op. push(17) 17 push(23) 17 23 stack (top to right) empty pop() 17 returns 23 push(29) 17 29 push(31) 17 29 31 pop() 17 29 returns 31 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise Illustration op. push(17) 17 push(23) 17 23 stack (top to right) empty pop() 17 returns 23 push(29) 17 29 push(31) 17 29 31 pop() 17 29 returns 31 pop() 17 returns 29 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise Illustration op. push(17) 17 push(23) 17 23 stack (top to right) empty pop() 17 returns 23 push(29) 17 29 push(31) 17 29 31 pop() 17 29 returns 31 pop() 17 returns 29 pop() empty returns 17 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Stack Behaviour A stack is a container abstraction that holds a collection of items in a linear bottom to top order. Operations push(x) Add a new item x to the top of the stack pop() Remove and return the item at the top of the stack. Illegal if stack is empty. is empty() Return True if stack is empty, False otherwise Illustration op. push(17) 17 push(23) 17 23 stack (top to right) empty pop() 17 returns 23 push(29) 17 29 push(31) 17 29 31 pop() 17 29 returns 31 pop() 17 returns 29 pop() empty returns 17 pop() ERROR KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 4 / 15

Postfix evaluation algorithm Split expression into constituent elements: Operators: +,,, / Operands: unsigned integers (or floats) Use stack to hold intermediate results, initially empty, holds result at alg s conclusion. For each element: if operand: push it onto stack if operator: pop top two items, apply operator to these, push result back onto stack KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 5 / 15

Illustration 1 2 3 + elt. stack Remarks empty 1 1 1 pushed 2 1 2 2 pushed 3 1 2 3 3 pushed 1 6 3, 2 popped, 6 = 2 3 pushed + 7 6, 1 popped, 7 = 1 + 6 pushed Result 7 on top of stack KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 6 / 15

Illustration 3 2 1 elt. stack Remarks empty 3 3 3 pushed 2 3 2 2 pushed 1 3 2 1 1 pushed 3 1 1, 2 popped, 1 = 2 1 pushed 7 1, 3 popped, 2 = 3 1 pushed Result 2 on top of stack KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 7 / 15

Elements of a Python implementation Implement Stack idea using class definition. Parse input expression into constituent elements using regular expressions Evaluation algorithm a doddle KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 8 / 15

Implementing Stack class Stack(): def init ( self ): self. items = [] def push( self, new item): self. items. append(new item) def pop( self ): if self.is empty (): raise Exception( Stack error :.... ) else : return self. items. pop() Function is empty omitted for brevity. KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 9 / 15

Splitting expression into constituent elements tokens = re.compile(r [ +/ ] (\d+(\.\d+)?) ) for t in tokens. finditer ( expression ): # Code to handle element t as per algorithm KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 10 / 15

Splitting expression into constituent elements tokens = re.compile(r [ +/ ] (\d+(\.\d+)?) ) for t in tokens. finditer ( expression ): # Code to handle element t as per algorithm The [-+/*] bit captures the four operators The \d+(\.\d+)? bit captures operands (ints or decimals) KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 10 / 15

Teeing things up values = Stack() operators = { + : lambda x, y: x + y, : lambda x, y: x y, : lambda x, y: x y, / : lambda x, y: x // y if type(x) == type(y) == int else x / y } expression = input( Please enter postfix expression : ) KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 11 / 15

Evaluation algorithm for t in tokens. finditer ( expression ): tkn = t.group(). strip () if tkn in operators : # Handle operator case else : # Handle operand case print( Result is %s. % str(values.pop())) KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 12 / 15

Evaluation algorithm cont d for t in tokens. finditer ( expression ): tkn = t.group(). strip () if tkn in operators : # Handle operator case else : if tkn. isdigit (): values. push(int(tkn)) else : values. push(float(tkn)) KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 13 / 15

Evaluation algorithm cont d for t in tokens. finditer ( expression ): tkn = t.group(). strip () if tkn in operators : val2 = values.pop() val1 = values.pop() action = operators[tkn] new val = action(val1, val2) values. push(new val) else : # Handle operand case KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 14 / 15

Evaluation algorithm cont d for t in tokens. finditer ( expression ): tkn = t.group(). strip () if tkn in operators : val2 = values.pop() val1 = values.pop() action = operators[tkn] new val = action(val1, val2) values. push(new val) else : if tkn. isdigit (): values. push(int(tkn)) else : values. push(float(tkn)) KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 15 / 15

Infix evaluator Can develop alg. based on similar principles for infix notation. Could always use Python s eval function: result = eval(expression) print( result ) Warning: eval and its sister exec can represent security risk if used on unvetted strings. KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17 16 / 15