Transcript Monday 22 October

| categories: Transcripts

After answering several questions about assignment 4 and the midterm next Wednesday we looked at a simple programming challenge.

Write a function named mymax that takes an array and returns the maximum value in the array without using any of the numpy functions. In other words reproduce how np.max might work.

The words "write a function named mymax that takes an array" tell us we need something like

def mymax(A):

So we know the first line anyway. Now, now many of the elements of A do we need to examine to determine the maximum? All of them. So we need a loop.

def mymax(A):
    for v in A:

We want to compare v to our current estimate of the biggest value so we need an if.

def mymax(A):
    for v in A:
        if v > biggest:

What do we want to do when v is bigger? Remember it as the new biggest.

def mymax(A):
    for v in A:
        if v > biggest:
            biggest = v

But what is the initial value of biggest? The first time through this loop it won't have a valuve and we will get an error. Let's remedy that by giving it a value before the loop starts.

def mymax(A):
    biggest = A[0]
    for v in A:
        if v > biggest:
            biggest = v

Almost done. Now we just need to return biggest at the end. This is a very common pattern. Initialize a variable, do something to it in a loop, then use its value.

def mymax(A):
    biggest = A[0]
    for v in A:
        if v > biggest:
            biggest = v
    return biggest

The position of that return is critical. If we indent it too far we won't repeat the loop for every value in A.

Kelsey wondered how we could write one that returned all the winners from the comparision. Here is kmax, can you see how it works?

def kmax(A):
    biggest = [ A[0] ]  # a list with one element
    for v in A:
        if v > biggest[-1]:  # if it is bigger than the last (biggest so far)
            biggest.append(v)  # add a new biggest so far
    return biggest  # return all of them as a list

For your programming pleasure, try coding your own version of np.argmax, np.sum, or np.cumsum.