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.

214 Trees<br />

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

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

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

9<br />

The second example implies that we consider a single operand <strong>to</strong> be a kind of<br />

product. This definition of “product” is counterintuitive, but it turns out <strong>to</strong> be<br />

useful.<br />

Now we have <strong>to</strong> deal <strong>with</strong> compound products, like like 3 * 5 * 13. We treat<br />

this expression as a product of products, namely 3 * (5 * 13). The resulting<br />

tree is:<br />

*<br />

3<br />

*<br />

5 13<br />

With a small change in getProduct, we can handle an arbitrarily long product:<br />

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

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

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

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

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

else:<br />

return a<br />

# this line changed<br />

In other words, a product can be either a single<strong>to</strong>n or a tree <strong>with</strong> * at the root, a<br />

number on the left, and a product on the right. This kind of recursive definition<br />

should be starting <strong>to</strong> feel familiar.<br />

Let’s test the new version <strong>with</strong> a compound product:<br />

>>> <strong>to</strong>kenList = [2, ’*’, 3, ’*’, 5 , ’*’, 7, ’end’]<br />

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

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

2 3 5 7 * * *<br />

Next we will add the ability <strong>to</strong> parse sums. Again, we use a slightly counterintuitive<br />

definition of “sum.” For us, a sum can be a tree <strong>with</strong> + at the root, a product<br />

on the left, and a sum on the right. Or, a sum can be just a product.

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

Saved successfully!

Ooh no, something went wrong!