[SOLVED] Find the maximum integer among three integers with Python

Table of Contents

Issue

I need to write a function to find the maximum value among three inputs.

Ex: If the inputs are:

5
7
9

the output is:

9

Ex: If the inputs are:

-17
-8
-2

the output is:

-17
def max_magnitude(user_val1, user_val2, user_val3):
    if (user_val1 >= user_val2) and (user_val1 >= user_val3):
        max = user_val1
        
    elif (user_val2 >= user_val1) and (user_val2 >= user_val3):
        max = user_val2
    
    else:
        max = user_val3
    
    return max    
     
def main():
    user_val1 = int(input())
    user_val2 = int(input())
    user_val3 = int(input())
    
    print(max_magnitude(user_val1, user_val2, user_val3))
    

if __name__ == '__main__':

    main()

enter image description here

Solution

Fix

For each condition value is biggest add the opposite value is lowest

def max_magnitude(user_val1, user_val2, user_val3):
    if (user_val1 >= user_val2 and user_val1 >= user_val3) or \
            (user_val1 <= user_val2 and user_val1 <= user_val3):
        return user_val1

    elif (user_val2 >= user_val1 and user_val2 >= user_val3) or \
            (user_val2 <= user_val1 and user_val2 <= user_val3):
        return user_val2

    return user_val3

Improve

  • use *args as parameter, tp handle any amount of values
  • use builtin max
  • with key abs (absolute value).
def max_magnitude(*args):
    return max(args, key=abs)

max(abs(i) for i in args) doesn’t work as it would return the absolute value of the answer, not the original value

Answered By – azro

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.