-1

I've built a function to calculate median (as the name indicates).

The function receives a list of ints, for instances [4,5,5,4] and should output 4,5.

The code:

def median(lst):
    lst.sort()
    a=int(len(lst)/2)
    if len(lst) % 2 == 0:
        med=float((lst[a]+lst[a-1])/2)
    else:
        med=lst[a]
    return med
print(median([4,5,5,4]))

This works fine when using Python 3.x but not in Python 2.x. What am i doing wrong?

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145

1 Answers1

1

The problem is you are assuming the division operator is the same in both Python 2 and 3. Instead (adapted from mhlester):

  • in Python 2, / is integer division (int inputs);

  • in Python 3, / is float division;

  • in Python 2 and 3, // is integer division.

In order to achieve what you are looking for, there's different workarounds. For instances:

  1. You can make sure to have at least one operand of your division in float. Eg:

    def median(lst):
        lst.sort()
        a=int(len(lst)/float(2))
        if len(lst) % 2 == 0:
            med=float((lst[a]+lst[a-1])/float(2))
        else:
            med=lst[a]
        return med
    print(median([4,5,5,4])) 
    
  2. You can use the import from __future__ import division (this needs to be done before any other imports). Eg:

    from __future__ import division
    
    def median(lst):
        lst.sort()
        a=int(len(lst)/2)
        if len(lst) % 2 == 0:
            med=float((lst[a]+lst[a-1])/2)
        else:
            med=lst[a]
        return med
    print(median([4,5,5,4]))
    
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
  • 1
    Thanks, I started programming just 4 days ago and the nuances are pretty obscure to me. Your answer really cleared things up! – Vedant Khanna Dec 24 '18 at 14:50