The code below reveals how to move cheeses on three stools:
As we have practiced so far, it has a base case which print "move top cheese from source to destination", and after tracing the general case, the function ultimately will print every steps it used of moving cheeses from the first stool to the last stool. What the general case does is moving all but the bottom cheese from the source(1st) stool to the intermediate(2ed) stool and having destination(3rd) stool as intermediate stool; it is recursive. Next, move the bottom cheese from the source(1st) stool to the destination(3rd) stool; it is not recursive as n is not greater than 1. Lastly, move all the cheese on the intermediate stool to the destination, using the source(1st) stool as intermediate stool; it is recursive.
In our assignment, we need to move between four stools. This would greatly reduced the move steps because not like moving between three stools we have one intermediate stool now we have two. Therefore, to find how many cheeses will be moved in the first place in order to get minimum number of moves became a big challenge. Works on them really help me get better understanding on programming.
Other things I found hard to understand are scopes and namespaces. They are new and abstract concept for me. According to the notes online, a namespace is "mapping from names to objects", such as built-in names, global names and local names, and each of them are created at different stages and have different lifetimes. Another important fact to notice is the local namespace is created when the function is called, and "forgotten" when the function exits. The orders in python are innermost scope (local), enclosing scopes (nonlocal), global, and built-in names.
The example below is about how global and nonlocal methods work and the clearer sight of namespaces and scopes. When we first assign spam = "test spam", it is local in scope_test(); "spam = "local spam"" is inside do_local(), therefore after the function is called, the value is forgotten, spam still refers to "test spam". After we nonlocal spam in the do_nonlocal(), we assign new value to spam, "spam = "nonlocal spam"" and it is still true in scope_test(). Moreover, global spam make "spam = "global spam"" true in global name spam. However, we still print local spam inside scope_test(). Finally, when we exit the scope_test(), the global name spam refers to "global spam".
The output of the example:
Thanks for reading!
about hanoi, we smplify the 4 tower into three steps! a sub 4 tower cases and two 3 tower cases. if the question is just asking the minimim steps , it will be extremely simple since in 3 tower case, it is just 2**n -1.
ReplyDelete