Could someone please help with the correct way or there opinion on this. I have written code which is below that is supposed to take input from a text file arrange one line in order and state which is the minimum number then the same on the next line for the maximum number and finally for the average of all numbers.
My code:
from statistics import mean
def number1():
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())
number1()
I was told this was incorrect. Below is the code suggested that I should use but after clearing the indentation which I think is correct. I only get an output of the average line.
Suggested code:
outfile = open("output.txt", "w")
with open("input.txt") as f:
for line in f:
# clean line and split into operator and data
operator, data = line.lower().strip().split(":")
line = line.split(":")
operator = line[0].lower().strip()
data = line[1].strip().split(",")
# parse data into list of integers
# data = [int(x) for x in data.split(",")]
# convert numbers in list to integer
newData = []
for x in data:
newData.append(int(x))
# min(), max(), sum(), len()
# determine operation to perform on number list variable
if operator == "min":
result = min(newData)
elif operator == "max":
result = max(newData)
elif operator == "avg":
result = sum(newData) / len(newData)
# create output string
report_line = "The {} of {} is {}.\n".format(operator, newData, result)
outfile.write(report_line)
outfile.close()
You can use below logic.
Say your text file is data.txt with below content
Use the below code to insert all the number into list and find min and max.