Question

can you finish implementing the functions below ********************************************************************************************************** import urllib.request from typing import List, TextIO #...

can you finish implementing the functions below
**********************************************************************************************************

import urllib.request
from typing import List, TextIO


# Precondition for all functions in this module: Each line of the url
# file contains the average monthly temperatures for a year (separated
# by spaces) starting with January.  The file must also have 3 header
# lines.
DATA_URL = 'http://robjhyndman.com/tsdldata/data/cryer2.dat'


def open_temperature_file(url: str) -> TextIO:
    '''Open the specified url, read past the three-line header, and 
    return the open file.
    '''
    ...


def avg_temp_march(f: TextIO) -> float:
    '''Return the average temperature for the month of March
    over all years in f.
    '''

    # We are providing the code for this function
    # to illustrate one important difference between reading from a URL
    # and reading from a regular file. When reading from a URL,
    # we must first convert the line to a string.
    # the str(line, 'ascii') conversion is not used on regular files.
    
    march_temps = []

    # read each line of the file and store the values
    # as floats in a list
    for line in f:
        line = str(line, 'ascii') # now line is a string
        temps = line.split()
        # there are some blank lines at the end of the temperature data
        # If we try to access temps[2] on a blank line,
        # we would get an error because the list would have no elements.
        # So, check that it is not empty.
        if temps != []:
            march_temps.append(float(temps[2]))

    # calculate the average and return it
    return sum(march_temps) / len(march_temps)


def avg_temp(f: TextIO, month: int) -> float:
    '''Return the average temperature for a month over all years
    in f. month is an integer between 0 and 11, representing
    January to December, respectively.
    '''
    ...


def higher_avg_temp(url: str, month1: int, month2: int) -> int:
    '''Return either month1 or month2 (integers representing months in
    the range 0 to 11), whichever has the higher average temperature 
    over all years in the webpage at the given URL.  If the months have
    the same average temperature, then return -1.
    '''
    ...


def three_highest_temps(f: TextIO) -> List[float]:
    '''Return the three highest temperatures, in descending order, 
    over all months and years in f.
    '''
    ...


def below_freezing(f: TextIO) -> List[float]:
    '''Return, in ascending order, all temperatures below freezing 
    (32 degrees Fahrenheit), for all temperature data in f. Include 
    any duplicates that occur.
    '''
    ...
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the code for the following question :

Code :

import urllib.request
from typing import List, TextIO

DATA_URL = 'http://robjhyndman.com/tsdldata/data/cryer2.dat'

def open_temperature_file(url: str) -> TextIO:
    openUrl = urllib.request.urlopen(url)
    read_data = []
    readUrl = openUrl.readlines()
    for i in range(3,len(readUrl)):
        line = readUrl[i]
        read_data.append(str(line.decode('utf-8')))
    return  read_data


def avg_temp_march(f: TextIO) -> float:
    march_temps = []

    for line in f:
        line = str(line, 'ascii')  # now line is a string
        temps = line.split()
        if temps != []:
            march_temps.append(float(temps[2]))
    return sum(march_temps) / len(march_temps)


def avg_temp(f: TextIO, month: int) -> float:
    average_temp = float()
    for row in f:
        row  = row.split()
        if row != []:
            row = float(row[month])
            average_temp = average_temp + row
    return  average_temp / 12


def higher_avg_temp(url: str, month1: int, month2: int) -> int:
    read_Temp_file = open_temperature_file(url)
    averge_temp_month1 = (avg_temp(read_Temp_file, month1))
    averge_temp_month2 = avg_temp(read_Temp_file, month2)
    if  averge_temp_month1 > averge_temp_month1:
        return  averge_temp_month1
    elif averge_temp_month1 < averge_temp_month2:
        return  averge_temp_month2
    else:
        print("Both mont have same average temprature")
        return  averge_temp_month1

def three_highest_temps(f: TextIO) -> List[float]:
    years = [1964,1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974,1975]
    highest_temp_list = {}
    three_hihest_temp = []
    row_index = -1
    print("Three Highest Temp For each Year :")
    for row in f:
        row  = row.split()
        if row != []:
            row_index = row_index + 1
            for index in range(len(row)):
                highest_temp_list[index] = row[index]
            count = 0
            print(years[row_index], end=":--> ")

            for i in sorted(highest_temp_list, key=highest_temp_list.get, reverse=True):
                print(i, " : ",highest_temp_list.get(i), end="         ")
                count = count + 1
                if count == 3:
                    break
            print()

def below_freezing(f: TextIO) -> List[float]:
     
    temp_below_freezeing_point = []
    freezing_point = float(32)
    for row in f:
        row = row.split()
        if row != []:
            for data in row:
                temp = float(data)
                if temp < freezing_point:
                    temp_below_freezeing_point.append(temp)
    sorted_data = sorted(temp_below_freezeing_point, key= lambda  x : float(x))
    return  sorted_data
read_file =   open_temperature_file(DATA_URL)
print("Avg Temp : ", avg_temp(read_file, 1))
print("Avg Temp : ", avg_temp(read_file, 2))
print("Higher avg temp between two month : ",higher_avg_temp(DATA_URL, 1,2))
three_highest_temps(read_file)
print("Temp Below Freezing Point : ",below_freezing(read_file))

------------------------------------------------------------------------------------------------------------------------------------------------

I'm also providing the screenshots so that you may not face any indentation issues:

OutPut :

Add a comment
Know the answer?
Add Answer to:
can you finish implementing the functions below ********************************************************************************************************** import urllib.request from typing import List, TextIO #...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a class called TemperatureFile. • The class has one data attribute: __filename • Write get...

    Write a class called TemperatureFile. • The class has one data attribute: __filename • Write getter and setter for the data attribute. • Write a “calculateAverage” function (signature below) to calculate and return average temperature of all temperatures in the file. def calculateAverage(self): • Handle possible exceptions Write a main function: • Create a file ('Temperatures.txt’) and then use “write” method to write temperature values on each line. • Create an object of the TemperaureFile with the filename (‘Temperatures.txt’) just...

  • Please use python. You can import only: from typing import Dict, List from PIL import Image...

    Please use python. You can import only: from typing import Dict, List from PIL import Image import random Questions are: --------------------------------------------------------------------------------------------------------------------------------- 1. def rotate_picture_90_left(img: Image) -> Image: """Return a NEW picture that is the given Image img rotated 90 degrees to the left. Hints: - create a new blank image that has reverse width and height - reverse the coordinates of each pixel in the original picture, img, and put it into the new picture """ -----------------------------------------------------------------------------------------------------------------------------------    2. def...

  • I don't understand step 3 also can someone check if I did the setTemps method right?...

    I don't understand step 3 also can someone check if I did the setTemps method right? Step 2: Temps Class For lab9 we will be using arrays to store the high temperatures for a given month and perform some simple statistics for them. You will create a Temps class to store the values and perform the calculations. (Data that you use for this lab was obtained from the national weather service and city‐data.com – from June 2004) Create a new...

  • Use your Food class, utilities code, and sample data from Lab 1 to complete the following...

    Use your Food class, utilities code, and sample data from Lab 1 to complete the following Tasks. def average_calories(foods):     """     -------------------------------------------------------     Determines the average calories in a list of foods.     foods is unchanged.     Use: avg = average_calories(foods)     -------------------------------------------------------     Parameters:         foods - a list of Food objects (list of Food)     Returns:         avg - average calories in all Food objects of foods (int)     -------------------------------------------------------     """ your code here is the...

  • Assignment 1 In this assignment you will be writing a tool to help you play the...

    Assignment 1 In this assignment you will be writing a tool to help you play the word puzzle game AlphaBear. In the game, certain letters must be used at each round or else they will turn into rocks! Therefore, we want to create a tool that you can provide with a list of letters you MUST use and a list of available letters and the program returns a list of all the words that contain required letters and only contain...

  • This is a python question. Start with this program, import json from urllib import request def...

    This is a python question. Start with this program, import json from urllib import request def main(): to_continue = 'Yes' while to_continue == 'yes' or to_continue == 'Yes': currency_code = input("Enter currency code: ").upper() dollars = int(input("Enter number of dollar you want to convert: ")) # calling the exchange_rates function data = get_exchange_rates() if currency_code in data["rates"].keys(): currency = data["rates"][currency_code] # printing the the currency value by multiplying the dollars amount. print("The value is:", str(currency * dollars)) else: print("Error: the...

  • The following is a program from Starting out with C++ by Toni Gaddis. I am getting the following error messages pertain...

    The following is a program from Starting out with C++ by Toni Gaddis. I am getting the following error messages pertaining to the lines: cin>>month[i].lowTemp; and months[i].avgTemp = (months[i].highTemp + month[i].lowTemp)/2; The error messages read as follows: error C2039: 'lowTemp': is not a member of 'std::basic_string<_Elem,_Traits,_Ax>' and it continues. The second error message is identical. The program is as follows: Ch. 11, Assignment #3. pg. 646. Program #4. //Weather Statistics. //Write a program that uses a structure to store the...

  • I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to...

    I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to guess its because I'm not using the swap function I built. Every time I run it though I get an error that says the following Traceback (most recent call last): File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 146, in <module> main() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 122, in main studentArray.gpaSort() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py",...

  • Write a program that demonstrates use of programmer - defined data structures. Please provide code! Thank...

    Write a program that demonstrates use of programmer - defined data structures. Please provide code! Thank you. Here are the temps given: January 47 36 February 51 37 March 57 39 April 62 43 May 69 48 June 73 52 July 81 56 August 83 57 September 81 52 October 64 46 November 52 41 December 45 35 Janual line Iranin Note: This program is similar to another recently assigned program, except that it uses struct and an array of...

  • Using C++ Part C: Implement the modified Caesar cipher Objective: The goal of part C is...

    Using C++ Part C: Implement the modified Caesar cipher Objective: The goal of part C is to create a program to encode files and strings using the caesar cipher encoding method. Information about the caesar method can be found at http://www.braingle.com/brainteasers/codes/caesar.php.   Note: the standard caesar cipher uses an offset of 3. We are going to use a user supplied string to calculate an offset. See below for details on how to calculate this offset from this string. First open caesar.cpp...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT