List and maximum numbers

Your first problem is at highest = List[0]. Since List is not guaranteed to have at least one item, you will have an error if List is empty. You should add a check:

def getMax4(List):
    if not List: # or if len(List) == 0:
        return -999
    ...

Another problem is that you define highest as the first item. Why? The first item could possibly be the highest only if it is divisible by four. You should set it to 0 so that even if there are no numbers divisible by four, it will still have the default of 0 that is required in the examples.

The next problem is that you are returning inside the loop. Wait until the loop is done before you try to return.

Once we fix all those, the problem is that -4 is better than 0 even though it is lower. We can simply add a check for not highest (highest is equal to 0). The new code looks like this:

def getMax4(List):
    if not List:
        return -999
    highest = 0
    for num in List:
        if num % 4 == 0 and (num > highest or not highest):
            highest = num
    return highest

Leave a Comment