Sunday, February 9, 2014

Week 5

In this week, we went over recursion some more, and I really think I'm finally starting to get it. On Monday, we went over the process of writing a recursive program for the movement of cheeses on three stools. I'm sure this is going to be useful for my assignment, but I'm still worried about how to write a program for four stools. Anyway, on Wednesday, we touched on names and where local, nonlocal, global, and built in module names stand on the name hierarchy.

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)

nonlocal turns the name spam into a local name inside the function scope_test
global turns the name spam into a global name in the entire module.

As for our lab, we worked on more recursion. I was happy that I was able to finish both of the required functions as well as one of the bonus ones. Here is the code if anyone is interested.

def find_num(SL: 'SearchList', n: int) -> bool:

    if n < SL[0]:
        return (find_num(SL[1], n) if isinstance(SL[1], list) else False)
    elif n > SL[0]:
        return (find_num(SL[2], n) if isinstance(SL[2], list) else False)
    elif n == SL[0]:
        return True
    
def freeze(x: object) -> object:

    if isinstance(x, list):
        return [freeze(item) if isinstance(item, list) else item for\
                item in x]
    else:
        return x    

def rev_string(s):

    string = ''
    for x in range(len(s) - 1, -1, -1):
        string += s[x]
    return string

p.s. we touched on methods a little bit more. 

class a:
    def b():

        return 2

if I did a.b(), it would return 2.
however, if I did this:
c = a()
c.b()

I would get an error because now the class a has an argument now, which is the name c.

No comments:

Post a Comment