Saturday, 8 February 2014

Week #5: Understanding Namespaces and an Assignment 1 Update

     This week in lecture the aspect I found to be most confusing was not recursion, it was the namespace example we were shown on Wednesday. At first I thought I understood it clearly because the theory made sense to me. Much like math equations have an order of operations (BEDMAS), names in python are given a certain level of priority based on where they are defined in python code. A python interpreter first searches for a given name locally (within the innermost function), and works its way outward through the nonlocal names, and global names, until it finally reaches the built-in names. However, I felt lost once we began to go through the following example:

          # local, nonlocal, global scope
def scope_test():
    def do_local(): # nested function --- only available inside scope_test()
        spam = "local spam"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)  
scope_test() 
print("In global scope:", spam)

     Everything seemed murky, and I didn't quite understand where certain results were coming from, or why certain results were being printed. I remembered the last time I felt this way was about the exceptions example we were shown in class. What had helped me the most in that situation was copying the example into Wing, and actually working with it myself. I decided to do that with this code as well, an it helped me immensely. For example, although it may have confused me in class, when I tried it myself I understood that  'After global assignment: test spam', was being printed because of the order of priority I had theoretically understood before hand. It was also interesting to note that 'nonlocal spam' overrode 'test spam'.

     As far as my progress on Assignment 1, I have finished implementing the actual game, but now I must complete the recursive element. That is, I must solve Anne Hoy's moving problem as efficiently as possible. I think, (as Sandra mentioned in her SLOG: http://sandracsc148slog.blogspot.ca/2014/02/week-5.html) I am going to find the lesson on the recursive solution to the problem using 3 pegs that we discussed in class, very helpful when finishing this assignment.

No comments:

Post a Comment