Home > database >  max magnitude: finding max magnitude among integers
max magnitude: finding max magnitude among integers

Time:11-06

import math
def max_magnitude(val1, val2, val3):
   
    
    if abs(val1) > abs(val2) and abs(val3):
        return(val1)
    elif abs(val2) > abs(val3) and abs(val1):
        return(val2)
    elif abs(val3) > abs(val2) and abs(val1):
        return(val3)
def main():
    val1 = int(input())
    val2 = int(input())
    val3 = int(input())
    
    print(max_magnitude(val1, val2, val3))
    


if __name__ == '__main__':
    main()

input: 25 0 -50 expected test: return correctly -50 but my output test : return incorrectly 25

someone help me to fix that error while texting

CodePudding user response:

Firstly, you have written a lot of unnecessary code. Let's simplify that by using map().

def max_magnitude(val1, val2, val3):
    return max([val1,val2,val3],key=abs) # Return the max value of abs

max() basically returns the maximum value present in an iterable. The key arg of max() helps us pass abs as an argument.

The whole code looks like this:

def max_magnitude(val1, val2, val3):
    return max([val1,val2,val3],key=abs) # Return the max value of abs
def main():
    val1 = int(input())
    val2 = int(input())
    val3 = int(input())
    print(max_magnitude(val1, val2, val3))
    
if __name__ == '__main__':
    main()

Thanks to @j1-lee → map() not needed

Docs:

max()

CodePudding user response:

It can be done in one line with sorted()

if __name__ == '__main__':
    val1, val2, val3 = int(input()), int(input()), int(input())
    print(sorted([val1, val2, val3], key=lambda x: abs(x))[-1])
25
0
-50
-50

CodePudding user response:

I think this is what you meant to do

import math

def max_magnitude(val1, val2, val3): 
    
    if abs(val1) > abs(val2) and abs(val1) > abs(val3):
        return(val1)
    elif abs(val2) > abs(val3) and abs(val2) > abs(val1):
        return(val2)
    elif abs(val3) > abs(val2) and abs(val3) > abs(val1):
        return(val3)
def main():
    val1 = int(input())
    val2 = int(input())
    val3 = int(input())
    
    print(max_magnitude(val1, val2, val3))
    


if __name__ == '__main__':
    main()
  • Related