Home > Back-end >  How to get just "3" and not "3.0?
How to get just "3" and not "3.0?

Time:06-14

import numpy as np

def median(x):
    y = np.median(x).
    return y

My output is "3.0" when it is supposed to be "3" the other answer is right which is "3.5"

CodePudding user response:

This result is due to the fact that the np.median() function returns a float, not an integer. If you want the result to return an integer if it's not a decimal value, then you can use the code below:

import numpy as np

def median(x):
    y = np.median(x)
    return int(y) if y%1==0 else y    

If we run print(median([4,3,1,5,2]), median([4,3,1,5,2,6])), the output will be: 3 3.5

CodePudding user response:

Try this:

import numpy as np

def median(x):
    y = np.median(x)
    if y % 1 == 0:
        y = np.int16(y)
    return y

print(median([4,3,1,5,2]), median([4,3,1,5,2,6]))
  • Related