Search code examples
pythonlistfunctionreadfilemedian

Python: How do I read a .txt file of numbers to find the median of said numbers without using median() call?


I am working on an assignment that requires us to read in a .txt file of numbers, then figure out a way to use the length of the list to determine the middle index of both odd/even lengths of number lists to calculate the median without using the median() call. I do not understand how I would go about this, anything helps! (I am also still faily new to Python)

debug = print

# assign name of file to be read
file = "numbers_even.txt"

# open file to be read
def get_median(med):
    with open(file, mode='r') as my_file:
    # assign middle index values for list    
        m2 = len(file) // 2
        debug("index2", m2)

        m1 = m2 -1

        value1 = file[m1]
        debug(m1, value1)

        value2 = file[m2]

        middle = (value1 + value2) / 2
        debug("val1:", value1, "val2:", value2, "mid", middle)
    # end with
# end function

get_median(file)

Solution

  • Assuming your text file (numbers_even.txt) looks something like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    

    You can do this:

    with open('numbers_even.txt','r') as f:
        median = f.readlines()
    
    if len(median) % 2 == 0:
        print(median[int(len(median)/2-1)])
    else:
        print((int(median[int(len(median)//2)])+int(median[int(len(median)//2-12)]))/2)
    

    Output:

    5.5