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

Python Question Using lists, write the function non_unique(list) that takes a list list as argument. It...
Python Question Using lists, write the function non_unique(list) that takes a list list as argument. It returns a list which duplicated elements remains and each duplicated element is followed by a number which shows how many times it appears. All elements in return list should be in the same order as their appearance in the original list. For example, given the input [‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘d’, ‘a’,‘e’], the function would return [‘a’, 3, ‘b’, 2]. Another example, ['abc',...
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 building a tik tac toe board using python and the function I am using...
I am building a tik tac toe board using python and the function I am using is not working to check to see if the board is full. I'll include the code for the board and the function to check if it is full. X's and O's are being inserted and the function is suppose to stop running when is_full(board) returns True. ch is either x or o board = []    for i in range(3):     board.append([])     for j...
write a member function in C++ , that takes two lists and return list that contain...
write a member function in C++ , that takes two lists and return list that contain the merge of the two lists in the returned list: first insert the first list and then the second list  
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.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT