Language:EN
Pages: 2
Rating : ⭐⭐⭐⭐⭐
Price: $10.99
Page 1 Preview
end tree getsum printtreepostorder are almost done

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.

You are viewing 1/3rd of the document.Purchase the document to get full access instantly

Immediately available after payment
Both online and downloadable
No strings attached
How It Works
Login account
Login Your Account
Place in cart
Add to Cart
send in the money
Make payment
Document download
Download File
img

Uploaded by : Patrick Alvarez

PageId: ELIACC40A5