FAQ: Code Challenge: Control Flow - Max Number

There is plenty of documentation to explain how max() works. The purpose of this exercise is not to study the built in function, but to create a one of our own that performs the same task, using an algorithm.

1 Like

This is my code. In case of call - print(max_num(5, 3, 3)) - it prints only 5, although it seems to be “It’s a tie!” also, because of if (not elif) operators. Am I wrong?

def max_num(num1, num2, num3):
if num1 > num2 and num1 > num3:
return num1
if num2 > num1 and num2 > num3:
return num2
if num3 > num1 and num3 > num2:
return num3
if num1 == num2 or num1 == num3 or num2 == num3:
return “It’s a tie!”
print(max_num(5, 3, 3))

Return means handing back data to the function call, thus when the code reaches the line return num1 the function ends, so it never does the tie comparison

I’m not a code god, just a learner. But I was thinking the same thing. I’ve been looking at the notes on W3schools at the same time as working through the Codecademy course, since encountering Codecademy’s use of untaught string formatting in an earlier solution. Something I saw on there while browsing through was the max() method which I used here. It’s comparatively short and seems to work:

def max_num(num1, num2, num3):
if num1 == max(num2, num3) or max(num1, num2) == num3:
return “It’s a tie!”
else:
return max(num1, num2, num3)

First, learn how to do long division, then pick up that calculator!

Python has a great many built-in functions, among them max() and min(). One tried and true teaching method is to have students code functions which are (more or less) the equivalent of certain built-ins, on the theory that it is always good exercise to learn to do something using loops and conditionals.

Should a learner be penalized for taking the initiative to reach out to Dr Google for advice? No, in my opinion, it is to be encouraged. But there is no harm (and possibly some good?) in knowing that you can do something “the hard way”, also.

This was my code:
def max_num(num1, num2, num3):
if num1 == num2 or num1 == num3 or num2 == num3:
return “It’s a tie!”
return max(num1, num2, num3)
It works

your if statement for checking for ties doesn’t necessarily work. If for example, you called

max_num(1,1,2)

your code would return “It’s a tie!” even though the max number isn’t in a tie with any other number.

I believe this is the most efficient way to make a max_num function:

def max_num(num1,num2,num3):
	nums = [num1, num2, num3]
	i=0
	while i<len(nums):
		if (nums[i]==nums[i-1]==max(nums)):
			return "It's a tie!"
		else:
			i+=1
	else:
		return max(nums)

What is this? If you’re going to reach for the built-in, may as well go for the gusto,

if count(max(nums)) > 1:
    return "It's a tie!"
return max(nums)

You’re totally right. My mistake. I’m pretty new to python.

1 Like