Reduce is a built in function that takes a function, a sequence, and a value (called 'initial'). Reduce takes the sequence and applies the function to every value in the sequence. If an initial is given, the initial will be placed at the beginning of the items.
I had a lot of trial and error before I figured out how to use this built-in function. Eventually I came up with a simple example that showed how it worked:
def add(x, y):
return x + y
def add_list(t: list):
return reduce(add, t, 0)
With this function you would be able to add up all the items in a list (basically sum()).
Reduce seems to be very useful for minimizing the amount of code you have to write to reach your desired result.
We also learned about local, non-local, and global scopes. Assigning a value locally means to assign a value deep within the function. Assigning a value non-locally means to assign a value in the outermost scope that is still within the function. Assigning a value globally means to assign a value in the global scope (e.g. I can call the value in the Python shell). Writing nonlocal before assigning something to a variable allows me to assign values in the outer (but no global) scope and writing global before assigning something to a variable allows me to assign values in the global scope.
I had a hard time figuring out how to use nonlocal and global because typing in help(nonlocal) or help(global) in the Python shell did nothing. So I turned to Google.
The last thing we learned was cache, the introduction of a dictionary into a recursive function to minimize the number of steps to complete its implementation, thereby significantly cutting down on running time. In class, we saw that using a dictionary instead of simply powering through recursive calls severly cut down on running time of the fibonacci sequence function. Referring to a dictionary to retrieve a value is much faster than recursively calling a function over and over again, since we already know what the value is. We cut down on a lot of redundancy.
I am still trying to completely understand this concept but the general idea is clear to me. I still find it a little difficult to trace through this process, especially with the fibonacci sequence function that Danny showed us.
By reading the slogs of my classmates, it seems that most people understand the reduce function and the idea of local, non-local, and global scopes. But some people, myself included, seem to be having trouble with the idea of introducing a dictionary to cut down on the number of steps to implement a recursive function (cache).
I will definitely try to incorporate these functions and ideas into my future code.