Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Max of 3 numbers
#1
Hi, so I am supposed to write a function to find the maximum of 3 numbers. Initially I wanted to write a function that takes in 3 values and analyzes each case by case , like this :

def Max ( x, y, z)
    if x > y and y > z
       print x
    elif 
       x > y and y < z
       print z 
     .... so on and so forth 
But I realized that it is very tedious because there are quite a few possible cases.

So I looked at the solution and this is what it gave :

def max_of_two( x, y ):
    if x > y:
        return x
    return y
def max_of_three( x, y, z ):
    return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))
But I don't understand how this code works. Isn't the code for max_of_two missing an else statement? Because it should return x if x > y and return y if x < y. I'm confused...
Reply
#2
The function does not need an else statement. If x > y then the function returns x and exits; in all other cases (else), it reaches the end of the if statement, continues with the rest of the function, and returns y.
Reply
#3
Function max_of_two compares two numbers and returns largest.

This statement:

max_of_two( x, max_of_two( y, z ))
First it evaluates and returns larger number from y and z max_of_two(y, z). Lets call it w. Then it evaluates and returns largest number from x and w (for better understanding just replace expression with its actual result, which will make second step: max_of_two(x, w)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,662 May-09-2019, 12:19 PM
Last Post: Pleiades

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020