Stacks II. Adventures in Notation. stacks2 1

Similar documents
Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

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

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

Stacks. The unorganized person s data structure. stacks 1

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

Infix to Postfix Conversion

STACKS AND QUEUES. Problem Solving with Computers-II

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

Stack Abstract Data Type

CS 211 Programming Practicum Spring 2017

CS 211 Programming Practicum Spring 2018

Prefix/Infix/Postfix Notation

Stack and Its Implementation

The Stack and Queue Types

CS 211 Programming Practicum Fall 2018

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal.

BBM 201 DATA STRUCTURES

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

BBM 201 DATA STRUCTURES

March 13/2003 Jayakanth Srinivasan,

Lab 7 1 Due Thu., 6 Apr. 2017

Chapter 3. Selections

Top of the Stack. Stack ADT

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

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

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

Project 1: Implementation of the Stack ADT and Its Application

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

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

Data Structures and Algorithms

CS W3134: Data Structures in Java

Stacks Calculator Application. Alexandra Stefan

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

Operators DECREASE in strength toward the Bottom

ECE 122 Engineering Problem Solving with Java

Linear Data Structure

CISC-235. At this point we fnally turned our atention to a data structure: the stack

Top of the Stack. Stack ADT

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

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

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

Stacks. Revised based on textbook author s notes.

Data Conversion & Scanner Class

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

CS Introduction to Data Structures How to Parse Arithmetic Expressions

Stacks. CONTENTS 3.1 Introduction 1. Stack as an abstract data type 2. Representation of a Stack as an array 3.2Applications of Stack.

Advanced Java Concepts Unit 3: Stacks and Queues

CSE 214 Computer Science II Stack

UNIT-II. Part-2: CENTRAL PROCESSING UNIT

Chapter 3: Operators, Expressions and Type Conversion

Types of Data Structures

3. Java - Language Constructs I

Operators & Expressions

More Programming Constructs -- Introduction

An Introduction to Trees

Assignment 5. Introduction

Fall, 2015 Prof. Jungkeun Park

Stacks and their Applications

Operators in java Operator operands.

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

JAVA OPERATORS GENERAL

DEEPIKA KAMBOJ UNIT 2. What is Stack?

Operators. Java operators are classified into three categories:

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

Prof. Navrati Saxena TA: Rochak Sachan

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Postfix (and prefix) notation

CMPSCI 187 / Spring 2015 Postfix Expression Evaluator

Assessment of Programming Skills of First Year CS Students: Problem Set

Assignment 4 Publication date: 27/12/2015 Submission date: 17/01/ :59 People in-charge: R. Mairon and Y. Twitto

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

Data Structure. Recitation IV

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

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

Stacks Fall 2018 Margaret Reid-Miller

1/30/2018. Conventions Provide Implicit Information. ECE 220: Computer Systems & Programming. Arithmetic with Trees is Unambiguous

Lecture Data Structure Stack

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

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Operators and Expressions

Stacks, Queues (cont d)

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Data Structures. Chapter 06. 3/10/2016 Md. Golam Moazzam, Dept. of CSE, JU

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #23 Loops: Precedence of Operators

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

PA3 Design Specification

A Simple Syntax-Directed Translator

Monday, November 13, 2017

CS 206 Introduction to Computer Science II

Lecture 4 Stack and Queue

CSC 222: Computer Programming II. Spring 2005

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

Chapter 2: Basic Elements of Java

Programming in C++ 5. Integral data types

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

Computer Components. Software{ User Programs. Operating System. Hardware

Transcription:

Stacks II Adventures in Notation stacks2 1

The trouble with infix... Rules for expression evaluation seem simple -- evaluate expression left to right, results of each sub-expression becoming operands to larger expression -- but All operators are not created equal -- multiplication & division take precedence over addition & subtraction... stacks2 2

The trouble with infix... So it isn t really all that simple -- we must first scan for higher-precedence operations, and evaluate these first -- and that s not so easy to program -- so In the calculator program, we rely on parentheses to tell us which operations to perform when -- hence the need for fullyparenthesized expression stacks2 3

Alternatives to infix -- prefix Prefix notation, a.k.a. Polish notation Operator precedes operands infix expression: A + B prefix expression: +AB Parentheses become unnecessary infix expression: (A + B) * C prefix expression: * + A B C stacks2 4

Converting from infix to prefix Write out operands in original order Place operators in front of their operands If there s a compound expression, the prefix expression may have two or more operators in a row If parentheses are not present, pay attention to precedence stacks2 5

Conversion examples A + B + C >>>>>> + + A B C A - B + C >>>>>> + - A B C A + (B - C) >>>>> + A - B C A * ((B + C) - D) / E >>> / * A - + B C D E A + B * C / D >>>> + A / * B C D A * B + C - D / E >>> - + * A B C / D E stacks2 6

Prefix evaluation scan left to right until we find the first operator immediately followed by pair of operands evaluate expression, and replace the used operator & operands with the result continue until a single value remains stacks2 7

Prefix Example + * / 4 2 3 9 // original expression + * 2 3 9 // 4/2 evaluated + 6 9 // 2*3 evaluated 15 // 6+9 evaluated stacks2 8

Another example * - + 4 3 5 / + 2 4 3 // original expression * - 7 5 / + 2 4 3 // 4+3 evaluated * 2 / + 2 4 3 // 7-5 evaluated * 2 / 6 3 // 2+4 evaluated * 2 2 // 6/3 evaluated 4 // 2*2 evaluated stacks2 9

Prefix summary Operands (but often not operators) same order as infix Expression designated unambiguously without parentheses Improvement on infix, but still not quite as simple to evaluate as one might wish -- have to deal with exceptions stacks2 10

Alternative II: Postfix Postfix is also known as reverse Polish notation -- widely used in HP calculators In postfix notation, operators appear after the operands they operate on As with prefix, operand order is maintained, and parentheses are not needed Postfix expression is not merely a reverse of the equivalent prefix expression stacks2 11

Postfix expression examples Simple expression: Original Expression: A + B Postfix Equivalent: A B + Compound expression with parentheses: original: (A + B) * (C - D) postfix: A B + C D - * Compound expression without parentheses: original: A + B * C - D postfix: A B C * + D - stacks2 12

Postfix expression evaluation Read expression left to right When an operand is encountered, save it & move on When an operator is encountered, evaluate expression, using operator & last 2 operands saved, saving the result When entire expression has been read, there should be one value left -- final result stacks2 13

Postfix evaluation using stack Postfix evaluation can easily be accomplished using a stack to keep track of operands As operands are encountered or created (through evaluation) they are pushed on stack When operator is encountered, pop two operands, evaluate, push result stacks2 14

Postfix calculator code import java.util.*; import java.util.regex.*; public class PostfixCalculator { private String expression; private Stack<Double> nums; public static final Pattern CHARACTER = Pattern.compile("\\S.*?"); public static final Pattern UNSIGNED_DOUBLE = Pattern.compile("((\\d+\\.?\\d*) (\\.\\d+))([ee][-+]?\\d+)?.*?"); stacks2 15

Postfix calculator code public PostfixCalculator () { nums = new Stack<Double>(); expression = ""; } stacks2 16

Postfix calculator code public void evalpostfix () { Scanner expression = new Scanner(this.expression); String next; do { if (expression.hasnext(unsigned_double)) { next = expression.findinline(unsigned_double); nums.push(new Double(next)); } stacks2 17

Postfix calculator code } else { next = expression.findinline(character); calculate(next); } } while (expression.hasnext()); stacks2 18

Postfix calculator code public void calculate (String n) { if (nums.size() < 2) throw new IllegalArgumentException("Input expression: " + expression + " invalid"); double op2 = nums.pop(); double op1 = nums.pop(); char op = n.charat(0); stacks2 19

Postfix calculator code } switch (op) { case '+': nums.push(op1 + op2); break; case '-': nums.push(op1 - op2); break; case '*': nums.push(op1 * op2); break; case '/': nums.push(op1 / op2); break; } stacks2 20

Postfix calculator code public double getresult() { if (nums.size() > 1 nums.isempty()) throw new IllegalArgumentException("Input expression: " + expression + " invalid"); return (double)nums.pop(); } public void setexpression (String e) { expression = e; } stacks2 21

Postfix calculator code public static void main (String [] args) { PostfixCalculator pc = new PostfixCalculator(); Scanner kb = new Scanner (System.in); String input; do { System.out.print ("Enter a postfix expression (or Q to quit: "); input = kb.nextline(); if (input.equalsignorecase("q")) System.out.println ("So long, and thanks for all the fish!"); stacks2 22

Postfix calculator code else { pc.setexpression(input); pc.evalpostfix(); System.out.println ("Your expression evaluates to: " + pc.getresult()); } } while (!input.equalsignorecase("q")); } } stacks2 23

Translating infix to postfix Postfix expression evaluation is easiest type to program Next task is to take an infix expression and translate it into postfix for evaluation Some basic assumptions: all operations are binary (no unary negative) expressions are fully parenthesized stacks2 24

Translating infix to postfix General method: move each operator to the right of its corresponding right parenthesis eliminate parentheses Example: (((A + B) * C) - (E * (F + G))) (((A B) + C) * (E (F G) +) * ) - A B+ C * E F G + * - stacks2 25

Pseudocode for translation Do { program if (left parenthesis) read & push else if (operand) read & write to output string else if (operator) read & push else if (right parenthesis) read & discard pop operator & write to output string pop & discard left parenthesis } while (expression to read) stacks2 26

OK -- but what if expression isn t fully parenthesized? We have to fall back on the rules for expression evaluation we know & love do expression in parentheses first do other operations in order of precedence -- in case of tie, leftmost sub-expression wins Example: A - ( B + C) * D - E order: 3 1 2 4 Postfix: A B C + D * - E - stacks2 27

Do Algorithm for expression conversion if (left parenthesis) read & push else if (operand) read & write to file else if (arithmetic operator)... // continued on next slide stacks2 28

Conversion algorithm continued while (stack not empty && stack.peek( )!= ( && op precedence lower than stack.peek( )) pop stack & write to file read op push op else // character should be ) // next slide... stacks2 29

Conversion algorithm continued read & discard right paren do pop stack & write to file while (stack.peek( )!= ( ) pop & discard left paren while (expression to read) // ends outer loop while (stack not empty) pop & write to file stacks2 30