Home > Blockchain >  Python - Read file I/O - Find average of each day temperature records
Python - Read file I/O - Find average of each day temperature records

Time:01-09

I have to write a Python function which records temperatures for different days. The temperature for the same day is stored on the same line.The first day is considered to be day 1, and each subsequent line of the file records the following days in sequential order (e.g. the 3rd line of data is collected from the 3rd day). If there was no data collected for a given day then the entire line will be blank. For example, The text file contains the following inputs for 6 days:

23 24.5
25
22.25 22.5

23.4
25.2 20.0

This file contains data collected for 6 days.

I am to define a function temp_record which takes a filename as a parameter. It reads the data from the parameter file and analyses the temperatures. The function should return a list of average temperatures per day. For example, the function returns the following list for the above text file:

[23.75, 25.0, 22.375, 0, 23.4, 22.6]

I wrote a code but it doesn't seem to work for all case types and I'm not sure what went wrong. Can someone help?

Here is the code I wrote:

def temp_record(filename):
input_file = open(filename,'r')
contents = input_file.read().split("\n")
sum_val = 0
lis = []
for string in contents:
    split_str = string.split(" ")
    for i in range(len(split_str)):
        if split_str[i] == '':
            split_str[i] = 0
        else:
            split_str[i] = float(split_str[i])
    
    ans = (sum(split_str)/len(split_str))
    if ans == 0.0:
        ans = 0
    lis.append(ans)
return lis

Thank you so much!

Here is a link to the screenshot of what the submission page says when I submit my code. https://i.stack.imgur.com/MUPYg.png

CodePudding user response:

When you do contents = input_file.read().split("\n") you get an additional element in contents list that gets computed to 0.

You can fix this like this:

def temp_record(filename):
    input_file = open(filename, 'r')
    # read all lines
    contents = input_file.readlines()
    sum_val = 0
    lis = []
    for string in contents:
        # lines end in \n use rstrip to remove it
        split_str = string.rstrip().split(" ")
        for i in range(len(split_str)):
            if split_str[i] == '':
                split_str[i] = 0
            else:
                split_str[i] = float(split_str[i])

        ans = (sum(split_str) / len(split_str))
        if ans == 0.0:
            ans = 0
        lis.append(ans)
    return lis

but this can be much shorter:

def temp_record(filename):
    result = []
    with open(filename, 'r') as fp:
        for line in fp:
            temps = line.split()
            avg_temp = sum(map(float, temps)) / len(temps) if temps else 0
            result.append(avg_temp if avg_temp > 0 else 0)

    return result

or even shorter if you want to play golfcode:

def temp_record2(filename):
    with open(filename, 'r') as fp:
        return list(map(lambda x: x if x > 0 else int(x), [sum(map(float, line.split())) / len(line.split()) if line.split() else 0 for line in fp]))

CodePudding user response:

Perhaps the hidden test that fails is with an input like:

-1 1
0
30

The first two days do have recorded temperatures, but their average is 0. Following the format of using floats for all other averages, the average should be 0.0, not 0 (as that would imply no temperature was collected for the day, when in fact one was).

If this is the issue, this could be fixed:

def temp_record(filename):
    input_file = open(filename,'r')
    contents = input_file.read().split("\n")
    sum_val = 0
    lis = []
    for string in contents:
        split_str = string.split(" ")
        for i in range(len(split_str)):
            if split_str[i] == '':
                split_str[i] = 0
            else:
                split_str[i] = float(split_str[i])
        
        ans = (sum(split_str)/len(split_str))
        if string == '':
            ans = 0
        lis.append(ans)
    return lis
  •  Tags:  
  • Related