In this exercise, the function is passed three numbers as parameters and determines the maximum value. How can the function return the maximum value for a list of numbers?

Answer

Python includes a max() function which does this task. If you pass the max() function a list of numbers, it will return the largest number in the list as shown in this example. If the exercise function was re-written to accept a list of numbers as a parameter, it could just call max() to find the largest value.

you could find the largest number with max() but you canâ€™t find the second largest or generate itâ€™s a tie.

I ended up using the below code after checking this post on stackoverflow

def max_num(num1,num2,num3):
l = [num1,num2,num3]
sort = sorted(l,reverse=True)
if sort[0] == sort[1]:
return "It's a tie!"
else:
return sort[0]

This adds the numbers to a list and sorts by largest.
I then check to see if the largest and second largest are equal, if they are return the string.
else return the largest number.

No, it doesnâ€™t. It returns 1, because the if statement will be evaluated first and you will exit the function once the first True condition is met, which is that 1 and 1 are equal

If you actually run the function, youâ€™ll see that it prints â€śItâ€™s a tie!â€ť

It does so because or (just as bitwise or as used here for some reason) stops processing (â€śis short-circuitedâ€ť) when the first True-returning expression is reached, and in this case, that is the that is the first one, (num2 == num3). That causes the if block to run and return â€śItâ€™s a tie!â€ť

But thatâ€™s not the behavior we want. The instructions say: The function should return the largest of these three numbers. If any of two numbers tie as the largest, you should return "It's a tie!", so you would want this to return 2, because thatâ€™s the highest number and youâ€™re evaluating for equality first. So if you have two numbers that are equal, but lower than the max, youâ€™re going to get the wrong result

def max_num(num1, num2, num3):
maximum = max(num1, num2, num3)
if (maximum == num1 or maximum == num2) and maximum == num3:
return "It's a tie!"
elif maximum == num1 and maximum == num2:
return "It's a tie!"
else:
return maximum

Just posting this here for people struggling with this as I did. The real issue with this task is just testing the max_num against the other numbers to find if and two are equal to the max. This was as concise as I could formulate it with my current knowledge.

Thereâ€™s another list command that counts the number of times that one value appears in a list. You can use it to identify Ties. The command is .count()

It kinda works except for e.g. max_num(5, -10, -10) (as one of the examples from the exercise shows). The problem here is that 5 is clearly the biggest number yet your code will print â€śItâ€™s a tie!â€ť. (I made the same mistake, therefore I know it)