1. Introduction to Time Complexity (answer = None)

Screen Link:
https://app.dataquest.io/m/476/time-complexity-of-algorithms/1/introduction-to-time-complexity

Questions regarding code segment contained in asterisks

def maximum(values):
    **answer = None** 
    for value in values: 
        if answer == None or answer < value: 
            answer = value 
    return answer 

Just curious, what purpose does this initial ‘answer = None’ accomplish? Thank you

Let me try to nudge you in the right direction by asking you another question: How would you create this function without that line of code?

Would it be the same as answer = 0?

What should maximum([-2, -3]) be? Answer this for yourself without using the function.

Now use the function with your suggestion and see what happens.

I’m getting the same answer for answer = None vs answer = 0. Does this mean the two are interchangeable?

I’m so sorry, Shawn! I had a lapse in judgment and I was trying to drive to the wrong conclusion.

They are interchangeable for the most part! The only difference I can think of is how they handle the empty list, but that’s an implementation detail that is not important for this screen.

The solution won’t return anything, your version will return 0, which isn’t really true, but also not the point of this screen.

You mean that None can be used as an empty list but 0 cannot, correct?

And thanks Bruno, no worries!

Hi @shawn,

The reason for using None is to make sure that we replace answer by some value in the list in the first iteration. If you set the value to 0 or anything else it will also work. For example, 42:

def maximum(values):
    answer = 42 
    for value in values: 
        if answer == 42 or answer < value: 
            answer = value 
    return answer 

The reason why the specific value does not matter is that the conditions is always verified the first time the if conditions is executed.

However, when I read the code, to me, 42 feels less natural. The same goes for 0. Usually, when we use an explicit value, we also remove the answer == value condition:

def maximum2(values): 
   answer = 0  
   for value in values:  
       if answer < value:  
           answer = value  
   return answer

However, in this case, using any value if not correct anymore:

maximum2([-1, -2])
0

If you want to use a value and remove the answer == None condition, you need to use a value that is smaller than the maximum value in values. Using 0 will not work if the maximum is smaller than 0. What you can use is float('-inf').

For the minimum it is similar. You need to start with a value that is bigger than the minimum. In this case, you can use float('inf').