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...
In Python, Complete the longestWord() function to take a list as a parameter and return the...
In Python, Complete the longestWord() function to take a list as a parameter and return the length of the longest word in that list. Examples: longestWord(['Python', 'rocks']) returns 5 longestWord(['Casey', 'Riley', 'Jessie', 'Jackie', 'Jaime', 'Kerry', 'Jody']) returns 6 longestWord(['I', 'a', 'am', 'an', 'as', 'at', 'ax', 'the']) returns 3
Write a Python function that will return the index of an element in a list.1- The...
Write a Python function that will return the index of an element in a list.1- The function will receive a list of at least 5 numbers as a single argument when the function is called. 2. The function will ask the user to input a number and will find and return the index of that number in the list.3. If the number is not an element of the list, the function returns the string "unknown."
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...
Using Python 3, define mySum function that supposed to return the sum of a list of...
Using Python 3, define mySum function that supposed to return the sum of a list of numbers (and 0 if that list is empty), but it has one or more errors in it. Write test cases to determine what errors there are.
I am trying to write a python code to create a function that returns all possible...
I am trying to write a python code to create a function that returns all possible dimensions (reshaping) for an input matrix, can someone explains the math and write a python code with explaining all the steps and give me a test cases, and please explain if there is more than one approach. so if we have 1*8 matrix we should return 1*8, 2*4,4*2,8*1 def reshaping(M) should return a n ORDERED list AND the all possible reshaped matrices
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:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT