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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

20.5 Building an expression tree 213<br />

The next function, getNumber, handles operands. If the next <strong>to</strong>ken in <strong>to</strong>kenList<br />

is a number, getNumber removes it and returns a leaf node containing the number;<br />

otherwise, it returns None.<br />

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

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

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

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

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

Before continuing, we should test getNumber in isolation. We assign a list of<br />

numbers <strong>to</strong> <strong>to</strong>kenList, extract the first, print the result, and print what remains<br />

of the <strong>to</strong>ken list:<br />

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

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

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

9<br />

>>> print <strong>to</strong>kenList<br />

[11, ’end’]<br />

The next method we need is getProduct, which builds an expression tree for<br />

products. A simple product has two numbers as operands, like 3 * 7.<br />

Here is a version of getProduct that handles simple products.<br />

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

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

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

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

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

else:<br />

return a<br />

Assuming that getNumber succeeds and returns a single<strong>to</strong>n tree, we assign the<br />

first operand <strong>to</strong> a. If the next character is *, we get the second number and build<br />

an expression tree <strong>with</strong> a, b, and the opera<strong>to</strong>r.<br />

If the next character is anything else, then we just return the leaf node <strong>with</strong> a.<br />

Here are two examples:<br />

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

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

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

9 11 *

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

Saved successfully!

Ooh no, something went wrong!