class BTNode:
’’’Binary Tree node.’’’
def __init__(self, data, left=None, right=None):
’’’ (BTNode, object, BTNode, BTNode) -> NoneType
Create BTNode (self) with data
and children left and right.
’’’
self.data, self.left, self.right = data, left, right
The use of the last line is smart!
Once we knew what a binary tree is, we learnt some methods used in this structure, for example, to evaluate it. The use of eval is said to be important, as in this line:
return eval(str(evaluate(b.left)) + b.data + str(evaluate(b.right)))
eval(...)
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
However, I still have problem understanding how to use the 'eval' function. What does global and local refer to? I think I'm going to ask the TA in tomorrow's practical.
Furthermore, I learned the three orders, which are inorder, preorder and postorder.
Inorder is from left to right, as it was given in the class:
if root is None:
pass
else:
inorder_visit(root.left, perform)
perform(root)
inorder_visit(root.right, perform)
Preorder is to evaluate from the root to the leaves, which goes like this:
perform(root)preorder_visit(root.left, perform)preorder_visit(root.right, perform)And postorder is skipping the root and evaluate the leaves first, which I find a little bit hard to keep track of while tracing the order using a picture. However, it gets a lot easier just using the codes. That's to say, well, computer is smarter than me...preorder_visit(root.left, perform)preorder_visit(root.right, perform)perform(root)I also find it interesting that a recursion can be written in the way above and not necessarily using the form of return (...(c) for all the c in ...)Above are the things I've learned this week, and more left to do for tomorrow's practical.Fighting Dark Fox!Ciao!Dark Fox
No comments:
Post a Comment