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.

212 Trees<br />

20.5 Building an expression tree<br />

In this section, we parse infix expressions and build the corresponding expression<br />

trees. For example, the expression (3+7)*9 yields the following tree:<br />

*<br />

+<br />

9<br />

3<br />

7<br />

Notice that we have simplified the diagram by leaving out the names of the attributes.<br />

The parser we will write handles expressions that include numbers, parentheses,<br />

and the opera<strong>to</strong>rs + and *. We assume that the input string has already been<br />

<strong>to</strong>kenized in<strong>to</strong> a <strong>Python</strong> list. The <strong>to</strong>ken list for (3+7)*9 is:<br />

[’(’, 3, ’+’, 7, ’)’, ’*’, 9, ’end’]<br />

The end <strong>to</strong>ken is useful for preventing the parser from reading past the end of the<br />

list.<br />

As an exercise, write a function that takes an expression string and<br />

returns a <strong>to</strong>ken list.<br />

The first function we’ll write is getToken, which takes a <strong>to</strong>ken list and an expected<br />

<strong>to</strong>ken as arguments. It compares the expected <strong>to</strong>ken <strong>to</strong> the first <strong>to</strong>ken on the list:<br />

if they match, it removes the <strong>to</strong>ken from the list and returns true; otherwise, it<br />

returns false:<br />

def getToken(<strong>to</strong>kenList, expected):<br />

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

del <strong>to</strong>kenList[0]<br />

return True<br />

else:<br />

return False<br />

Since <strong>to</strong>kenList refers <strong>to</strong> a mutable object, the changes made here are visible <strong>to</strong><br />

any other variable that refers <strong>to</strong> the same object.

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

Saved successfully!

Ooh no, something went wrong!