Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the maximum integer among three integers with Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading