0
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"

  • Here's a couple of ideas: 1) Convert the median value to [`int`](https://docs.python.org/3/library/functions.html#int) before printing. 2) Use [string formatting](https://docs.python.org/3/library/string.html#formatstrings) to change how the value is displayed. – 0x5453 Jun 13 '22 at 16:12
  • @0x5453. That won't help for the case that's correctly reporting 3.5 – Mad Physicist Jun 13 '22 at 16:13
  • 1
    That is expected as the documentation for [np.median](https://numpy.org/doc/stable/reference/generated/numpy.median.html) indicates that: *If the input contains integers or floats smaller than float64, then the output data-type is `np.float64`. Otherwise, the data-type of the output is the same as that of the input. If out is specified, that array is returned instead.* – jrd1 Jun 13 '22 at 16:13
  • Does this answer your question? [Formatting floats without trailing zeros](https://stackoverflow.com/questions/2440692/formatting-floats-without-trailing-zeros) – Kraigolas Jun 13 '22 at 16:14

2 Answers2

2

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

0

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]))