Question

In: Computer Science

Deliverables There is one deliverable for this assignment hw4.py Make sure the script obeys all the...

Deliverables

There is one deliverable for this assignment

  • hw4.py

Make sure the script obeys all the rules in the Script Requirements page.

Specification

The file has entries like the following

Barnstable,Barnstable,1
Bourne,Barnstable,5
Brewster,Barnstable,9
...

This script should create a dictionary where the county is the key and then total number of cases for the country is the value.

The script should print the name of the county with the highest number of cases along with the total cases.

The script must have 3 functions

  • open_file_read
  • cases_dictionary_create
  • highest_cases

This script must read in a text file with case numbers for all cities in Massachusetts along with their counties.

open_file_read

This function must have the following header

def open_file_read(filename):

It must try to create a file object for reading on the file whose name is given by the parameter filename.

If it is succesfull in creating the file object it should return the object.

If it is cannot create the object it should print an error message and return None.

cases_dictionary_create

This function must have the following header

def cases_dictionary_create(file):

This function reads a file and creates a dictionary where the keys are counties and the values are total cases.

  • The function returns this dictionary.

highest_cases

This function must have the following header

def highest_cases(county_cases):

The function

Script for this assignment

Open an a text editor and create the file hw4.py.

You can use the editor built into IDLE or a program like Sublime.

Test Code

Your hw4.py file must contain the following test code at the bottom of the file

filename = input("File name: ")
file = open_file_read(filename)
if file:
        cases = cases_dictionary_create(file)
        max_county, max_cases = highest_cases(cases)
        print(max_county,max_cases)

For this test code to work, you must copy cities_counties_cases.txt to your machine.

To do this use FileZilla to copy the file cities_counties_cases.txt f rom /home/ghoffman/course_files/it117_files into the directory that holds your hw4.py script.

Run the script entering cities_counties_cases.txt when prompted.

You should see

$ ./hw4.py 
File name: cities_counties_cases.txt
Worcester 455

Suggestions

Write this program in a step-by-step fashion using the technique of incremental development.

In other words, write a bit of code, test it, make whatever changes you need to get it working, and go on to the next step.

  1. Create the file hw4.py.
    Enter the headers for open_file_read, cases_dictionary_create and highest_cases.
    Under each header write the Python statement pass.
    Run the script.
    Fix any errors you find.
  2. Replace the pass statement in open_file_read with the body of the code from your hw2.py.
    Copy the first two lines of the test code into the bottom of the file.
    Run the scrip entering both a real filename and the name of a file that does not exists.
    Fix any errors you find.
  3. Remove the pass statement from cases_dictionary_create.
    Create the empty dictionary county_cases,
    Write a for loop that prints every line in the file.
    Copy the next two lines of the test code into your script.
    Run the script entering cities_counties_cases.txt when prompted.
    Fix any errors you find.
  4. Remove the print statement.
    You will have to use the split string method on each line in the file to assign values to the variables city, county and cases, but you need to use "," as the argument to split.
    Use either one of the techniques found in Class Exercise 2 or Class Exercise 3 to assign values to the variables.
    Write and assignment statement that converts cases to an integer.
    Print the value of the three variables.
    Run the script.
    Fix any errors you find.
  5. Remove the print statement.
    Now you are going to have to create entries in the dictionary county_cases, but this will take some thinking.
    You need to write an if statement that checks whether the value of county is already in the dictionary.
    If it is, you and the value of cases to the current value of cases in the dictionary and store that as the new value for county.
    If it is not already in the dictionary, create a new value entry with county as the key and cases as the value.
    Outside the for loop print the dictionary county_cases.
    Run the script.
    Fix any errors you find.
  6. Remove the print statement.
    In it's place write a statement to return county_cases.
    Remove the pass statement from highest_cases.
    In it's place write a for loop that loops through the entries in the dictionary.
    Inside the loop get the value of the current entry and assign it to the variable cases.

    Print county and cases For each entry.
    Outside the for loop return two empyy strings.
    If you don't you will get a runtime error when you run the script.
    Add the next line in the test code to the bottom of the script.
    Run the script.
    Fix any errors you find.
  7. Now you are going to have to find the county with the highest number of cases.
    You should use the same technique used in Class Exercise 3.
    Above the for loop assign the variable max_cases the value 0 and assign max_county the empty string.
    Remove the print statement inside the for loop.
    Write and if statement that checks whether the value of cases is greater than max_cases.
    If it is, set max_caes to the value of cases and max_county to county. Outside the for loop return max_county and max_cases.
    Copy the last line of the test code into the script.
    Run the script.
    Fix any errors you find.

Solutions

Expert Solution

CODE -

# Function to create a file object for reading on the file whose name is given by the parameter

# and return the file object if successful in creating file object.

def open_file_read(filename):

    # Opening the file

    cases_file = open(filename)

    # Returning the file object if file is opened successfully

    if cases_file:

        return cases_file

    else:

        # Printing error message and returning None if file can't be opened.

        print("File cannot be Opened.")

        return None

# Function to read file and create and return dictionary containing county names and cases

def cases_dictionary_create(file):

    # Creating empty dictionary

    cases_dict = {}

    # Reading file line by line

    for line in file:

        # Seperating city name, county name, and cases from the file which is seperated by comma

        line_list = line.split(",")

        # Adding county name and case to the dictionary if county name is not already in the dictionary

        if line_list[1] not in cases_dict:

            cases_dict[line_list[1]] = int(line_list[2].strip())

        # Adding no. of cases to the cases of the corresponding county if county name is already in the dictionary

        else:

            cases_dict[line_list[1]] += int(line_list[2].strip())

    # Returning the dictionary

    return cases_dict

# Function to find and return county name and cases with highest no. of cases.

def highest_cases(county_cases):

    # Initializing max_county to empty string

    max_county = ""

    # Initializing max_cases to 0

    max_cases = 0

    # Iterating over each county in the dictionary

    for county in county_cases:

        cases = county_cases[county]

        # Checking if no. of cases for current county is greater than max_cases.

        # If yes, assigning current county name to max_county and no. of cases of current county to max_cases

        if cases > max_cases:

            max_county = county

            max_cases = cases

    # Returning name of county and no. of cases of county with max no. of cases

    return max_county, max_cases

# Testing the script.

filename = input("File name: ")

file = open_file_read(filename)

if file:

    cases = cases_dictionary_create(file)

    max_county, max_cases = highest_cases(cases)

    print(max_county,max_cases)

SCREENSHOTS -

If you have any doubt regarding the solution, then do comment.

Do upvote.


Related Solutions

Deliverables There is one deliverable for this assignment hw6.py Make sure the script obeys all the...
Deliverables There is one deliverable for this assignment hw6.py Make sure the script obeys all the rules in the Script Requirements page. Specification The script must have 3 functions: get_args create_python_file print_directory get_args This function must have the following header: def get_args(arg_number): This function takes as its parameter an integer. The function should look at the number of command line arguments that the script gets when it is run. If the number of command line arguments is less than the...
Due Sunday, November 1st at 11:59 PM Deliverables There is one deliverable for this assignment hw7.py...
Due Sunday, November 1st at 11:59 PM Deliverables There is one deliverable for this assignment hw7.py Make sure the script obeys all the rules in the Script Requirements page. Specification Your script must print a Kelvin to Fahrenheit conversion table and between a minimum and maximum values, and a Fahrenheit to Kelvin conversion also between a minimum and maximum values. Here is the formula for converting Kelvin to Fahrenheit Here is the formula for converting Fahrenheit to Kelvin The script...
Write a script called script2-4.py that takes a person's delivery order as inputs, totals all the...
Write a script called script2-4.py that takes a person's delivery order as inputs, totals all the items and calculates the tax due and the total due. The number of inputs is not known. You can assume that the input is always valid. (i.e no negative numbers or string like "cat"). Use a loop that takes the prices of items as parameters that are floats, counts the number of items, and sums them to find the total. You must also use...
Write a script called script2-4.py that takes a person's delivery order as inputs, totals all the...
Write a script called script2-4.py that takes a person's delivery order as inputs, totals all the items and calculates the tax due and the total due. The number of inputs is not known. You can assume that the input is always valid. (i.e no negative numbers or string like "cat"). Use a loop that takes the prices of items as parameters that are floats, counts the number of items, and sums them to find the total. You must also use...
Write a script called script2-4.py that takes a person's delivery order as inputs, totals all the...
Write a script called script2-4.py that takes a person's delivery order as inputs, totals all the items and calculates the tax due and the total due. The number of inputs is not known. You can assume that the input is always valid. (i.e no negative numbers or string like "cat"). Use a loop that takes the prices of items as parameters that are floats, counts the number of items, and sums them to find the total. You must also use...
Make sure to include comments that explain all your steps (starts with #) Make sure to...
Make sure to include comments that explain all your steps (starts with #) Make sure to include comments that explain all your steps (starts with #) Write a program that prompts the user for a string (a sentence, a word list, single words etc.), counts the number of times each word appears and outputs the total word count and unique word count in a sorted order from high to low. The program should: Display a message stating its goal Prompt...
Assignment Requirements Write a python application that consists of two .py files. One file is a...
Assignment Requirements Write a python application that consists of two .py files. One file is a module that contains functions used by the main program. NOTE: Please name your module file: asgn4_module.py The first function that is defined in the module is named is_field_blank and it receives a string and checks to see whether or not it is blank. If so, it returns True, if not it return false. The second function that is defined in the module is named...
ASSIGNMENT Discuss the concept of "proof" as it relates to science. Make sure to provide at...
ASSIGNMENT Discuss the concept of "proof" as it relates to science. Make sure to provide at least one example in your discussion to facilitate the concept of proof.
the assignment is to compare and contrast two ads. Make sure the ads are similar enough...
the assignment is to compare and contrast two ads. Make sure the ads are similar enough to be compared and different enough to be contrasted: two soap ads, two cereal ads, two ads that are for baby products, etc 1 page
You have three questions to answer for this assignment. Read over the questions and make sure...
You have three questions to answer for this assignment. Read over the questions and make sure to answer all parts. Each answer needs to be a minimum of 250 words. Use supply and demand analysis to explain why the quantity of word processing software exchanged increases from one year to the next. Some people will pay a higher price for brand name goods. For example, some people buy Rolls Royces and Rolex watches to impress others. Does knowingly paying higher...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT