210k views
3 votes
Write a function maxTemp which takes a filename as string argument and returns the maximum temperature as float type for the week. Input file will contain temperature readings for each day of the week. Your function should read each line from the given filename, parse and process the data, and return the required information. Your function should return the highest temperature for the whole week. Empty lines do not count as entries, and should be ignored. If the input file cannot be opened, return -1. Remember temperature readings can be decimal and negative numbers. Each line of the file contains two elements, separated by commas (,) DAY,TEMPERATURE Monday,52 Note: The split() function is provided, and functions as it does in the homework assignments, to make parsing the output easier. Recall that split takes a string s and splits it at the input delimiter sep, to fill the array words[] up to a capacity of max_words. The return value of split is the number of actual words the string is split into.

1 Answer

3 votes

Answer:

#section 1

def maxTemp(filename):

import pathlib

f = pathlib.Path(filename)

f.exists()

if f.exists():

f = open(filename, "r")

#section 2

next(f)

res = [int(sub.split(',')[1]) for sub in f]

maxdata = (res[0])

for i in range(len(res)-1):

if maxdata < res[i]:

maxdata = res[i]

index = res.index(maxdata)

f.close()

#section 3

li = []

a = open(filename, "r")

for line in a:

line = line.strip()

li.append(line)

a.close()

return (li[index+1])

else:

return -1

print(maxTemp("new.csv"))

Step-by-step explanation:

#section 1:

The function maxTemp is defined. We import pathlib in other to check if the file exists, if it does we carry on with opening the file and if it doesn't the program returns -1.

#section 2:

We start splitting the sub-lists from the second line i.e next(f). For each line we take the second index element and convert it to an integer.

res = [int(sub.split(',')[1]) for sub in f]

The maximum number is gotten by using the if statement to compare all elements in the list. The index of the maximum item in the list is collected.

the file is then closed.

#section 3 :

The file is re-opened and all the lines are striped and passed into a new list and the index recovered from section 2, is used to get the day with the highest temperature and the line is returned.

Write a function maxTemp which takes a filename as string argument and returns the-example-1
User Pib
by
5.7k points