Median


#1

could somebody explain to me how it suppose to work i know that i have to make an empty variable
then iterate through the argument then add len(thing) [thing which is in the argument] divided by 2
could someone explain to me about what do the exercise mean by even numbers and non-even i know what is the even numbers but what do they want me to do with it


#2

import math

evenList = [1,2,3,4]
oddList = [1,2,3]

def median(list):
    if len(list) % 2 == 0:
        x = int(len(list) / 2)
        return (list[x] + list[x-1]) / 2
    else:
        return list[math.floor(len(list) / 2)]


print(median(evenList))
print(median(oddList))

you need to use int values to access arrays, so math.floor and int cast will enforce that.
For even length lists, you have 2 values that are the middle, so median is the 2 values divided by 2.
For odd length lists, the median is the direct middle, which math.floor will give you since

len(oddList) will be 3, 3 / 2 = 1.5
math.floor(1.5) = 1
0,1,2 available indexes. median = 1


#3

The even numbers and non-even numbers means that you need to create a function that find the median of lists that have an even amount of numbers or lists that have an odd amount of numbers. The len(lst) is just something you can use to set your conditions. eg.

if len(lst) % 2 == 0:
    ...
else:
    ...

#4

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