7 Expression Evaluation

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

ExpressionEvaluation

Chapter6
EECS268
Dr.DouglasNiehaus

EECS268

Dr.DouglasNiehaus20082011

Introduction
Evaluatingexpressionsisaclassicapplication
contextforbothgrammarsandstacks
Grammarspermitparsingoftheexpressionsand
creatingdatastructuresthatrepresentthe
expressionsemanticscorrectly
Stacksareusefulforevaluatingmanykindsof
expressions,mostobviouslyalgebraicexpressions
a*bc,a/b*c,((c+16)/b)+42
Recallthathumansmostcommonlyuseinfixnotation
fortheseexpressions,i.e.valopval
Problem:infixgrammarisnotacomplete
specificationofexpressionsemantics
Operatorprecedenceandparenthesesarealso
required
EECS268
Dr.DouglasNiehaus20082011
2

Introduction

Solution:useprefixorpostfixnotationsincetheir
grammarsaredefinitive,unambiguous,without
needingprecedencerulesorparentheses
SimpleAlgebraicExpressionGrammars
(1)infix=infixoperatorinfix|operand|(infix)
(2)prefix=operatorprefixprefix|operand
(3)postfix=postfixpostfixoperator|operand
Example:
InfixPrefixPostfix
abcPrefix:abcPostfix:abc
a(bc)Prefix:abcPostfix:abc

EECS268

Dr.DouglasNiehaus20082011

Introduction

Wethuswanttobeableto
(1)Evaluatepostfix(prefix)expressions,and
(2)Convertfrominfixtopostfix(prefix)expression.
Evaluatingpostfixusingastackisamazinglyeasy
oncethebasicpatternisunderstood
Usingastacktoconvertfrominfixtopostfixisalso
fairlysimple,butiscomplicatedbytheoperator
precedenceandparenthesissemantics
Postfixgrammar:
<postfix>=<identifier>|<postfix><postfix><operator>
<identifier>=a|b||z
<operator>=+||*|/

EECS268

Dr.DouglasNiehaus20082011

PostfixExpressionEvaluation

Wecanusestacktohelpevaluateapostfix
expression,whilereadingtheexpressionelements
(tokens)fromlefttoright
Operandsarepushedonthestack
Operatorspop2operandsandpushresults
Stackcontains1element,theresult,whenavalid
expressionisfullyevaluated
Algorithmisslightlymorecomplexifwepermit
negativenumbers(unaryoperator)
Noteweneedaseparateoperatorforthisin
postfix
Excellentexerciseforthestudent

EECS268

Dr.DouglasNiehaus20082011

PostfixExpressionEvaluation

Algorithm

foreachtokeninpostfixexpr
ifoperand,pushitsvalue;
ifoperator
popoperand2;
popoperand1;
result=operand1operatoroperand2;
pushresult;
valueattopofstackisresultofexpression;

Considertheexample
Infix:2*(3+4)
Postfix:234+*

EECS268

Dr.DouglasNiehaus20082011

PostfixExpressionEvaluation

EECS268

Dr.DouglasNiehaus20082011

PostfixExpressionEvaluation

Postfix:abc/de+f*Infix:((ab)/c)*((d+e)f

chactionstack
apusha
bpushab
popop2a
popop1
calc&pushab
cpushabc
/popop2ab
popop1
calc&push(ab)/c
dpush(ab)/cd
epush(ab)/cde
+popop2(ab)/cd
popop1(ab)/c
calc&push(ab)/c(d+e)
EECS268

chactionstack
fpush(ab)/c(d+e)f
popop2(ab)/c(d+e)
popop1(ab)/c
calc&push(ab)/c(d+e)f
*popop2(ab)/c
popop1
calc&push((ab)/c)*((d+e)f)

Dr.DouglasNiehaus20082011

InfixtoPostfixConversion

Assertionsaboutthealgorithm
Operandsneverchangeorder,infix postfix
Operandscanthusbewrittentothedeveloping
postfixstringassoonastheyareread
Operators,incontrast,movetotherightand
changeordertoreflectcalculationorder
Moveright:tofollowthetwooperands
Changeorder:duetooperatorprecedence
rulesandgroupingbyparentheses
Algorithmrequiresadatastructuretoholdasetof
pendingoperatorsuntilweknowtheycanbe
emittedintherightpositionwithinthepostfixstring

EECS268

Dr.DouglasNiehaus20082011

InfixtoPostfixConversion

Pendingoperatorsetcontentsshouldbeordered
fromlowesttohighestprecedence,withthehighest
precedencebeingtheoneweworkwith
Stackisgoodforthat,ifwefollowtherightpush
andpopruleswhenanoperatorisencounteredin
readingtheinfixtokenstream
1)ifthestackisemptyorifthenewoperatoris
higherprecedencethanthatontopofthestack
thenpushthenewoperator
2)Otherwisepopoperatorsandappendthemtothe
growingpostfixstringuntilcondition(1)applies
Hardtorealizeitwillwork,buteasytospecifyasan
algorithm

EECS268

10

Dr.DouglasNiehaus20082011

InfixtoPostfixConversion
createanemptypostfixstring;
whileoperatorstacknotempty{
createanemptyoperatorstack;
popoperator
while(nextsymbolSfrominfix!=NULL){
appendtopostfixstring
ifSisanoperandthen
}
appendStopostfixstring
elseifS==(then
pushS
elseifS==)then
popandappendoperators
untilmatching(found
else{
//mustbesomeotheroperator
while(operatorstacknotemptyAND
precedence(tos)>=precedence(S)AND
tos!=()
popoperator&appendtopostfixstring
pushS
}
}
EECS268

11

Dr.DouglasNiehaus20082011

InfixtoPostfixConversion

Converta(b+c*d)/etopostfixform

EECS268

12

Dr.DouglasNiehaus20082011

PostfixExpressionEvaluation

Convert(ab)/c*(d+ef/g)

chactionopstackPostfix
(push(
aoutput(a
push(a
boutput(ab
chactionopstackPostfix
)popto(ab
(push*(abc/
/push/ab
doutput*(abc/d
coutput/abc +push*(+abc/d
*popabc/ eoutput*(+abc/de
push*
pop*(abc/de+
push*(abc/de+
foutput*(abc/de+f
/push*(/abc/de+f
goutput*(/abc/de+fg
)popto(*abc/de+fg/
popuntilemptystackabc/de+fg/*
EECS268

13

Dr.DouglasNiehaus20082011

PrefixEvaluation

Reverseprefixandevaluateit
reversegivenprefixexpression;
scanthereversedprefixexpression;
foreachsymbolinreversedprefix
ifoperandthen
pushitsvalueontostackS;
ifoperatorthen{
popoperand1;
popoperand2;
computeresult=operand1opoperand2;
pushresultbackontostackS;
}
returnvalueattopofstack;

EECS268

14

Dr.DouglasNiehaus20082011

PrefixEvaluationExample

Prefix:*/abc+defReversed:fed+cba/*
chactionstack
fpushf
epushfe
dpushfed
+popop1fe
popop2f
calc&pushf(d+e)
popop1f
popop2
calc&push((d+e)f)
cpush((d+e)f)c
bpush((d+e)f)cb
apush((d+e)f)cba
popop1((d+e)f)cb
popop2((d+e)f)c
calc&push((d+e)f)c(ab)

EECS268

15

chactionstack
/popop1((d+e)f)c
popop2((d+e)f)
calc&push((d+e)f)((ab)/c)
*popop1((d+e)f)
popop2
calc&push((ab)/c)*((d+e)f)

Dr.DouglasNiehaus20082011

InfixtoPrefixConversion
reverseagivenlegalinfixstring(RIS);
createemptyreversedprefixstring(RPS);
createemptyoperatorstackS;
foreachsymbolchinRIS{
ifchisanoperand{
appendchtoRPS;
}elseifch==){
pushchonS;
}elseiftop(S)==({
pop&appendopstoRPSuntilmatching)
//discardthetwoparentheses
}else{//chmustbesomeotheroperator
while(SnotemptyAND
prec(top(S))>prec(ch)AND
top(S)!=)){
popop;
appendoptoRPS;
}
pushS
}
}
EECS268

16

while(!empty(S)){
popopfromS;
appendoptoRPS;
}
reverseRPS;
outputPrefixString

Dr.DouglasNiehaus20082011

InfixtoPrefixConversionExample

Infix:(ab)/c*(d+ef/g)Reversed:)g/fe+d(*c/)ba(

chactionopstackRPS
)push)
goutput)g
/push)/g
foutput)/gf
pop&out)gf/
push)gf/
eoutput)gf/e
+push)+gf/e
doutput)+gf/ed
(popuntil)gf/ed+
*push*gf/ed+

chactionopstackRPS
coutput*gf/ed+c
/push*/gf/ed+c
)push*/)gf/ed+c
boutput*/)gf/ed+cb
push*/)gf/ed+cb
aoutput*/)gf/ed+cba
(popuntil)*/gf/ed+cba
popuntilemptystackgf/ed+cba/*

Prefix:*/abc+de/fg

EECS268

17

Dr.DouglasNiehaus20082011

Summary

Varioususesifstacksconnectedtoparsingalgebraic
expressionsandevaluatingthem
Unlikelytobesomethingyouwriteasfreshcodeas
manylibrariesexistfordoingexpressionevaluation
andtheproblemcanbeapproachedinotherways
Butpossible
Goodpracticeforimaginingandtracingactionsof
codeusingstacks

EECS268

18

Dr.DouglasNiehaus20082011

You might also like