I spent most of time of this week working on the first assignment "Tower of Hanoi" which was really challenging. I was inspired by the hint given in class about how to move cheeses of three stools and finally figured out how to use the same recursive logic on four stools. This assignment definitely improves my programming ability and my understanding of recursion. I was quite excited about the animation of my solver when it automatically solved the puzzle using computer's amazing calculation speed.
I felt quite confused about the concept of namespaces and scopes learnt this week. I didn't know exactly how local scope and global scope work at the very beginning. By reading the scopes and namespaces from the python official website, I got Python searches for names in order from local scope, enclosing scope(nonlocal), global scope to built-in scope. We could add nonlocal assignment to change scope_test's binding and global assignment to change the module_level binding. These assignments are quite useful when assigning values to variables.Finally, I have a question:Context A:>>> x = 'outer' >>> def func(): print(x) x = 'inner' print(x)>>> func() Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> func() File "<pyshell#5>", line 2, in func print(x) UnboundLocalError: local variable 'x' referenced before assignmentcontext B:>>> def func(): print(x)>>> func() outerThis example is from: http://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-valueIt’s really interesting to see I can’t reference x in the local slope that is assigned in the global scope before assigning it in the local scope (context A), however it works without assigning it in the local scope (context B).Feel free to leave comments here. I hope to learn more from you.
Sunday, 9 February 2014
SLOG #3: Towers of Hanoi and Namespaces/Scopes
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment