Over 10 Million Study Resources Now at Your Fingertips


Download as :
Rating : ⭐⭐⭐⭐⭐
Price : $10.99
Language:EN
Pages: 2

End tree getsum printtreepostorder are almost done

20.5 Building an expression tree 213

If you are willing to play along with this definition, it has a nice property: we can represent any expression (without parentheses) as a sum of products. This property is the basis of our parsing algorithm.

getSum tries to build a tree with a product on the left and a sum on the right. But if it doesn’t find a +, it just builds a product.

def getNumber(tokenList):
if getToken(tokenList, ’(’):

x = getSum(tokenList)
getToken(tokenList, ’)’) return x
else:
x = tokenList[0]

214 Trees

The parser handled the parentheses correctly; the addition happens before the multiplication.

In the final version of the program, it would be a good idea to give getNumber a name more descriptive of its new role.

x = getSum(tokenList)

if not getToken(tokenList, ’)’):

The raise statement creates an exception; in this case we create a new kind of exception, called a BadExpressionError. If the function that called getNumber, or one of the other functions in the traceback, handles the exception, then the program can continue. Otherwise, Python will print an error message and quit.

As an exercise, find other places in these functions where errors can occur and add appropriate raise statements. Test your code with improperly formed expressions.

How It Works
Login account
Login Your Account
Add to cart
Add to Cart
Payment
Make payment
Document download
Download File
PageId: ELIACC40A5
img
Uploaded by :
MmMw8LyD
Page 1 Preview
end tree getsum printtreepostorder are almost done
Sell Your Old Documents & Earn Wallet Balance