06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

20.5 Building an expression tree 215<br />

If you are willing <strong>to</strong> play along <strong>with</strong> this definition, it has a nice property: we<br />

can represent any expression (<strong>with</strong>out parentheses) as a sum of products. This<br />

property is the basis of our parsing algorithm.<br />

getSum tries <strong>to</strong> build a tree <strong>with</strong> a product on the left and a sum on the right.<br />

Butifitdoesn’tfinda+, it just builds a product.<br />

def getSum(<strong>to</strong>kenList):<br />

a = getProduct(<strong>to</strong>kenList)<br />

if getToken(<strong>to</strong>kenList, ’+’):<br />

b = getSum(<strong>to</strong>kenList)<br />

return Tree (’+’, a, b)<br />

else:<br />

return a<br />

Let’stestit<strong>with</strong>9 * 11 + 5 * 7:<br />

>>> <strong>to</strong>kenList = [9, ’*’, 11, ’+’, 5, ’*’, 7, ’end’]<br />

>>> tree = getSum(<strong>to</strong>kenList)<br />

>>> printTreePos<strong>to</strong>rder(tree)<br />

9 11 * 5 7 * +<br />

We are almost done, but we still have <strong>to</strong> handle parentheses. Anywhere in an<br />

expression where there can be a number, there can also be an entire sum enclosed<br />

in parentheses. We just need <strong>to</strong> modify getNumber <strong>to</strong> handle subexpressions:<br />

def getNumber(<strong>to</strong>kenList):<br />

if getToken(<strong>to</strong>kenList, ’(’):<br />

x = getSum(<strong>to</strong>kenList)<br />

getToken(<strong>to</strong>kenList, ’)’)<br />

return x<br />

else:<br />

x = <strong>to</strong>kenList[0]<br />

if not isinstance(x, int): return None<br />

<strong>to</strong>kenList[0:1] = []<br />

return Tree (x, None, None)<br />

Let’s test this code <strong>with</strong> 9 * (11 + 5) * 7:<br />

# get the subexpression<br />

# remove the closing parenthesis<br />

>>> <strong>to</strong>kenList = [9, ’*’, ’(’, 11, ’+’, 5, ’)’, ’*’, 7, ’end’]<br />

>>> tree = getSum(<strong>to</strong>kenList)<br />

>>> printTreePos<strong>to</strong>rder(tree)<br />

9 11 5 + 7 * *

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!