Search code examples
pythonmathexternal-data-source

How to add math to your functions for writing to a text file


Could someone please help with how the correct way to add math to an already created function that writes output to a text file. The first task was to write the numbers to a output.txt file in values from lowest to highest, no matter the number or how many numbers. This I've done as per my code below. My problem is I now need to show the minimum number on the first line, the maximum number on the second and the average of the numbers on line 3. If anyone could help I would really appreciate the insight

Text file(input.txt)

min:1,2,3,4,5,6

max:18,25,32,14,15,62

avg:1,2,3,4,5,6

The output should be:

The min of [1,2,3,4,5,6] is 1

The max of [14,15,18,25,32,62] is 62

The avg of [1,2,3,4,5,6] is 3.4

As mentioned I already have a function to sort the numbers from low to high its just to do the math.

My code so far:

def number1():
    inputFile = open("input.txt", 'r')
    lineList = inputFile.readlines()
    fileHandle = open('inputcopy.txt', 'a')
    for line in lineList:
        numbers = [int(item) for item in line.split(':')[1].split(',')]
        numbers.sort()
        fileHandle.write("%s\n" % numbers)  
number1()

Solution

  • You need to parse the text numbers into ints so python can process them and map the mathematical operations for example like this:

    from statistics import mean
    
    
    with open('input.txt') as file:
        data = {
            line.split(':')[0]: sorted([int(value) for value in line.split(':')[1].split(',')]) for line in file.readlines()
        }
    
    functions = {'min': min, 'max': max, 'avg': mean}
    
    with open('output.txt', 'w') as file:
        file.writelines(
            f"The {function} of {values} is {functions[function](values)}\n" for function, values in data.items()
        )
    

    Which will give you:

    >>> The min of [1, 2, 3, 4, 5, 6] is 1
    >>> The max of [14, 15, 18, 25, 32, 62] is 62
    >>> The avg of [1, 2, 3, 4, 5, 6] is 3.5