Home > Back-end >  Find the maximum integer among three integers with Python
Find the maximum integer among three integers with Python

Time:03-01

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

CodePudding user response:

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

CodePudding user response:

  1. Don't use "max" as a variable name

  2. Do use max() as a function

  3. Just change the function input to *args, then take the max() of the abs() of the tuple:

def max_magnitude(*args): 
    output = max(abs(i) for i in args)
    return output if output in args else -output

Test code:

def max_magnitude(*args): 
    output = max(abs(i) for i in args)
    return output if output in args else -output

n1 = int(input())
n2 = int(input())
n3 = int(input())

print(max_magnitude(n1, n2, n3))

Examples:

#inputs
> 5
> 7
> 9
#outputs
> 9

#inputs
> -2
> -8
> -17
#outputs
> -17
  • Related