Median - Code Review


#1

Dear all,

I’m trying to get used with python and the I’m ok with majority part of the my code up to here, but the code below I think that can be better, I mean, I don’t think that solution proposed should use this amount of if’s… so please, could you guys let me know if this is ok or if there is some “better” way to do it?

The code is working as expected.


def median(lista):
  lista.sort()
  if len(lista) % 2 == 0 and len(lista) != 1:
    f_index = len(lista) / 2
    s_index = len(lista) / 2 - 1
    result = (lista[f_index] + lista[s_index]) / 2.0
    return result
  elif len(lista) == 1:
    index = lista[0]
    if index == 1:
      return 1
    else:
      return lista[0]
  else:
    index = len(lista) / 2
    return lista[index]


#2

its always a balance between the amount of code and readability

there are a few things you can shorten without sacrificing readability, like here:

if len(lista) % 2 == 0 and len(lista) != 1:

the and is not needed, 1 % 2 is 1, so if the list has a length of 1, len(lista) % 2 == 0 will never be true

this bit:

  elif len(lista) == 1:
    index = lista[0]
    if index == 1:
      return 1
    else:
      return lista[0]

is totally redundant. Your else clause:

  else:
    index = len(lista) / 2
    return lista[index]

can perfectly handle when the list contains a single item

you could compress this into a single line:

    f_index = len(lista) / 2
    s_index = len(lista) / 2 - 1
    result = (lista[f_index] + lista[s_index]) / 2.0

but then you are really sacrificing readability and maintainability, so leave that as it is


#3

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