Question

In: Computer Science

Python: I am currently a function that will return a list of lists, with the frequency...

Python: I am currently a function that will return a list of lists, with the frequency and the zip code. However, I am having a difficult time organizing the list in decreasing order of frequency. We are asked to use sort () and sorted () instead of lambda. The function will find 5 digit zip codes, and when it sees a 9-digit zip code, the function needs to truncate the last 4 digits. The following is an example of the outlook.

[ ... [9, '65616'], [8, '94573'], [8, '63103'] ...]

This is what I have so far:

import csv
updated_list = []

with open('Missouri_Beer_Wine.csv', 'r') as file:
reader = csv.reader (file, delimiter=',', quotechar='|')
for row in reader:
list = []
list.append(int(row[0]))
list.append(row[1])
updated_list.append (list)

new_list = sorted(updated_list)

print (new_list)

I am running into an error where it states there is a ValueError: invalid literal for int() with base 10: 'Business Name'. How would I go about this?

Solutions

Expert Solution

From your question I understood that you need to find the frequency of zip codes that occur and return the frequency and zip code as a list. eg: [ [ frequency-1 , zipcode-1 ] , [ frequency-2 , zipcode-2 ] , .... ]

so for this purpose

  • we need to parse the zipcode from the csv file and truncate it to 5 value.
  • Then count the number of each zipcode (This we can do efficiently by using a dictionary)
  • finally return the list

In the below code I assume the quotechar value as " . you can use the quotechar value according to the csv file.

import csv

with open('Missouri_Beer_Wine.csv', 'r') as file:
    reader = csv.reader (file, delimiter=',', quotechar='"')
    #initializing the dictionary for storing zipcode value
    zip_dict = {}
    for row in reader:
        # assuming row1 contains the zipcode
        # truncating the zip code to 5 values
        
        zipcode = row[1]
        truncated_zip=zipcode[:5]
        # print(truncated_zip)

        # storing zipcode value along with count in a dictionary
        if not truncated_zip in zip_dict:
            zip_dict[truncated_zip] = 1
        # if dictionary contains the zipcode we increment the value by 1
        else:
            zip_dict[truncated_zip] += 1
        
        # now zip_dict contains zipcodes along with its frequncies
        # converting it to a list of list using single line "list comprehension"
        output_list = [[val,key] for key, val in zip_dict.items()]
        
        # finally sort the list in reverse manner
        final_output_list = sorted(output_list,reverse=True)


    print(final_output_list)

Related Solutions

In python i want to create a function. The function will take in two linked lists...
In python i want to create a function. The function will take in two linked lists as the parameters. If one is shorter than the other then the shorter will be the length. I want to take the values from both linked lists and turn them into tuples. I then want these tuples to be put into a new linked list. I want to return that linked list. I want to do this using recursion and no helper functions or...
I am currently having trouble understanding/finding the errors in this python code. I was told that...
I am currently having trouble understanding/finding the errors in this python code. I was told that there are 5 errors to fix. Code: #!/usr/bin/env python3 choice = "y" while choice == "y": # get monthly investment monthly_investment = float(input(f"Enter monthly investment (0-1000):\t")) if not(monthly_investment > 0 and monthly_investment <= 100): print(f"Entry must be greater than 0 and less than or equal to 1000. " "Please start over.")) #Error 1 extra ")" continue # get yearly interest rate yearly_interest_rate = float(input(f"Enter...
In python I have a linked list. I want to create one function that takes in...
In python I have a linked list. I want to create one function that takes in one parameter, head. In the function, cur = head and next_cur = head.next. I want to return head and next_cur, except at the end of the function they will return alternating values from head. For example, if the these are the values in the linked list: 2, 3, 5, 7, 11 after the function head should return: 2, 5, 11 and next_cur should return:...
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
Python: How would I write a function using list comprehensions to list of integers into two...
Python: How would I write a function using list comprehensions to list of integers into two halves with the evens first, followed by odds? And on top of that, the numbers should be listed in their original order.
In python I want to create a function that takes in a linked list. Using recursion...
In python I want to create a function that takes in a linked list. Using recursion only, I want to check if the linked list is sorted. How do i do this?
Creating a list/tuple in python 2. Using a list of lists containing X’s and O’s to...
Creating a list/tuple in python 2. Using a list of lists containing X’s and O’s to represent a tic tac toe board, write code to check if the board has a winner.
In Python write a function with prototype “def dictsort(d):” which will return a list of key-value...
In Python write a function with prototype “def dictsort(d):” which will return a list of key-value pairs of the dictionary as tuples (key, value), reverse sorted by value (highest first) and where multiple keys with the same value appear alphabetically (lowest first).
Explain applying for a position that I am currently working as a para-educator, however, I am...
Explain applying for a position that I am currently working as a para-educator, however, I am hired as an adult assistant. We are a new school short staff so I am needed to do more of the Para-educator's work alongside taking care of my student. How do I explain that showing I am qualified to do the new posting of Para-educator?
This is in Python I am getting an error when I run this program, also I...
This is in Python I am getting an error when I run this program, also I cannot get any output. Please help! #Input Section def main(): name=input("Please enter the customer's name:") age=int(input("Enter age of the customer: ")) number_of_traffic_violations=int(input("Enter the number of traffic violations: ")) if age <=15 and age >= 105: print('Invalid Entry') if number_of_traffic_violations <0: print('Invalid Entry') #Poccessing Section def Insurance(): if age < 25 and number_of_tickets >= 4 and riskCode == 1: insurancePrice = 480 elif age >=...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT