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)