Could this code be simplified?

Not sure if people are still looking for the answers but this seems to have worked for me:
def max_num(num1, num2, num3):
if num1 > num2 and num1>num3:
return num1
elif num2>num1 and num2>num3:
return num2
elif num3>num1 and num3>num2:
return num3
elif num3==num2 and num3>num1:
return “It’s a tie!”
elif num2==num1 and num2>num3:
return “It’s a tie!”
elif num3==num1 and num3>num2:
return “It’s a tie!”

If anyone has any thought about writing this code in a more efficient way, please do feel free to reply.

That’s a lot of comparisons which is the first signal there must be a simpler way. Consider,

Step 1. Make the larger of the first two take the second position.

num1, num2 = num2, num1 if num1 > num2

Step 2. Make the larger of the last two take the last position.

num2, num3 = num3, num2 if num2 > num3

Step 3. Return num3

return num3
1 Like