Why my median of list function does not work


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/median?action=lesson_resume&link_content_target=interstitial_undefined

<In what way does your code behave incorrectly? Include ALL error messages.>
error message: median([4, 5, 5, 4]) returned 4 instead of 4.5

<What do you expect to happen instead?>

```python
<do not remove the three backticks above>
def median(seq):
  new=sorted(seq)
  med=0
  i=int(len(new))
  if i%2==0:
    med=(new[int(i/2)-1]+new[int(i/2)])/2
  elif i%2 !=0:
    med=new[int(i/2)]
  return(med)

#2

Hi @gigapro83146,

Will this statement perform float division or int division? .

  med=(new[int(i/2)-1]+new[int(i/2)])/2

As an experiment, try this …

print (4 + 5) / 2

What can be done to get a more satisfactory result?


#3

it gives 4 !!! why not give a 4.5


#4

In Python 2, the / operator performs int division when both the numerator and the denominator are ints. However, if one of the operands is converted to a float prior to the division process, the result will be a float.

For example, this will display a float result …

print float(4 + 5) / 2

You could use that technique in the median function.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.