Related questions
My program works with a CSV file with three columns: names, cities, and heights. I need to create a table that determines the difference in height from the average city size. This allows me to decide which two people have the minimum difference from the average. These difference tables must be in Python lists for each city. They must not use tuples, any dictionaries, named functions, or the key or lambda function.
To start with, could we try finding the average height in each city?
import csv
csv_data = []
with open("C:\\Users\\lucas\\Downloads\\sample-data.csv") as f:
reader = csv.reader(f)
for row in csv.reader(f):
csv_data .append(list(row))
f.close()
csv_data.pop(0)
difference_list = []
def Sorting_cities(data):
cities = []
for i in range(len(data)):
cities.append(data[i][1])
cities.sort()
return cities
city_list = Sorting_cities(csv_data)
print(city_list)
def Listing_cities(cities):
single_cities = []
for city in cities:
if city not in single_cities:
single_cities.append(city)
return single_cities
unique_cities = Listing_cities(city_list)
print(unique_cities)
def Counting_cities_and_people(single_cities, cities):
people_count = []
for city in single_cities:
count = cities.count(city)
people_count.append(count)
for k in range(len(single_cities)):
print(f'City: {single_cities[k]}, Population: {people_count[k]}')
return people_count
population = Counting_cities_and_people(unique_cities, city_list)
print(population)
def Find_heights(data):
heights = []
for city in unique_cities:
for d in data:
if city == d[1]:
heights.append(int(d[2]))
return heights
height_list = Find_heights(csv_data)
print(height_list)
def Find_names(data):
names = []
for city in unique_cities:
for d in data:
if city == d[1]:
names.append(d[0])
return names
name_list = Find_names(csv_data)
def Find_indexes(data):
index_list = []
index = 0
for height in data:
index_list.append(height)
index += 1
return index_list
indexes = Find_indexes(csv_data)
print(indexes)
def Find_average(height_list):
local_averages = []
for i in height_list:
heights = indexes[i][2]
average = sum(heights) / len(heights)
if heights == indexes[i][2]:
local_averages.append(average)
return average
avg = Find_average(height_list)
print(avg)
def Find_difference():
for height in height_list:
diff = abs(height - avg)
difference_list.append(diff)
index = 0
closest_to_average_height = 1000000000
closest_to_average_name = " "
second_closest_height = 1000000000
second_closest_name = "placeholder"
difference_list_two = difference_list.copy()
closest_to_average_diff = 1000000000
second_closest_to_average_diff = closest_to_average_diff
difference_list.sort()
for index in range(len(height_list)):
current_diff = difference_list_two[index]
if current_diff <= closest_to_average_diff:
second_closest_height = (height_list[index])
r = 0
for index in difference_list_two:
if index == difference_list[0]:
closest_to_average_diff = index
closest_to_average_height = height_list[r]
closest_to_average_name = name_list[r]
r += 1
newR = 0
for index in difference_list_two:
if index == difference_list[1] and name_list[newR] != closest_to_average_name:
second_closest_to_average_diff = index
second_closest_name = name_list[newR]
second_closest_height = height_list[newR]
newR += 1
City = "City"
most_average = "Most_Average"
Height = "Height"
next_most = "Second_Most_Average"
Next_height = "Height"
print(f"{City:^15} {most_average:^25} {Height:^6} {next_most:^25} {Next_height:^6}")
print(f'{city:^15} {closest_to_average_name:^25} {closest_to_average_height:^6} '
f'{second_closest_name:^25} {second_closest_height:^6}')
Trending nowThis is a popular solution!
Step by stepSolved in 5 steps with 3 images
What if this code could be done with user-defined functions? All other previous rules would continue to apply.
import csv
csv_data = []
with open("sample-data.csv") as f:
reader = csv.reader(f)
for row in reader:
csv_data.append(row)
f.close()
csv_data.pop(0)
# Find unique cities
cities = set()
for row in csv_data:
cities.add(row[1])
# Calculate average height for each city
city_heights = []
for city in cities:
heights_sum = 0
heights_count = 0
for row in csv_data:
if row[1] == city:
heights_sum += float(row[2])
heights_count += 1
avg_height = heights_sum / heights_count
city_heights.append((city, avg_height))
# Calculate difference from average height for each person
person_diffs = []
for row in csv_data:
name = row[0]
city = row[1]
height = float(row[2])
city_avg_height = None
for c, h in city_heights:
if c == city:
city_avg_height = h
break
diff = abs(height - city_avg_height)
person_diffs.append((name, city, diff))
# Find the two people with the minimum difference from the average for each city
for city, avg_height in city_heights:
city_person_diffs = []
for pd in person_diffs:
if pd[1] == city:
city_person_diffs.append((pd[0], pd[2])) # add name and height difference to list
n = len(city_person_diffs)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if city_person_diffs[j][1] < city_person_diffs[min_idx][1]:
min_idx = j
city_person_diffs[i], city_person_diffs[min_idx] = city_person_diffs[min_idx], city_person_diffs[i] # swap the elements
print("\n" + city + ":")
print("Average height: {:.2f}".format(avg_height))
print("{:<20} {:<20}".format("Name", "Difference"))
for i in range(min(2, n)):
name = city_person_diffs[i][0]
diff = city_person_diffs[i][1]
print("{:<20} {:<20.2f}".format(name, diff))
What if this code could be done with user-defined functions? All other previous rules would continue to apply.
import csv
csv_data = []
with open("sample-data.csv") as f:
reader = csv.reader(f)
for row in reader:
csv_data.append(row)
f.close()
csv_data.pop(0)
# Find unique cities
cities = set()
for row in csv_data:
cities.add(row[1])
# Calculate average height for each city
city_heights = []
for city in cities:
heights_sum = 0
heights_count = 0
for row in csv_data:
if row[1] == city:
heights_sum += float(row[2])
heights_count += 1
avg_height = heights_sum / heights_count
city_heights.append((city, avg_height))
# Calculate difference from average height for each person
person_diffs = []
for row in csv_data:
name = row[0]
city = row[1]
height = float(row[2])
city_avg_height = None
for c, h in city_heights:
if c == city:
city_avg_height = h
break
diff = abs(height - city_avg_height)
person_diffs.append((name, city, diff))
# Find the two people with the minimum difference from the average for each city
for city, avg_height in city_heights:
city_person_diffs = []
for pd in person_diffs:
if pd[1] == city:
city_person_diffs.append((pd[0], pd[2])) # add name and height difference to list
n = len(city_person_diffs)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if city_person_diffs[j][1] < city_person_diffs[min_idx][1]:
min_idx = j
city_person_diffs[i], city_person_diffs[min_idx] = city_person_diffs[min_idx], city_person_diffs[i] # swap the elements
print("\n" + city + ":")
print("Average height: {:.2f}".format(avg_height))
print("{:<20} {:<20}".format("Name", "Difference"))
for i in range(min(2, n)):
name = city_person_diffs[i][0]
diff = city_person_diffs[i][1]
print("{:<20} {:<20.2f}".format(name, diff))
- Find an example of a Python program on the Web that uses a dictionary in the code and share it. Post the link for the site. What is a Python dictionary? When should you use a dictionary rather than a list in Python?.What is happening in your programming example? Describe it in English as an algorithm.arrow_forwardYour friend is working on a Python program and can't decide whether to use astring, list, set, or dictionary. What general advice would you give them?For each, tell them one reason that they might choose that type of data over the others.TODO Type your reasons belowString:List:Set:Dictionary:arrow_forwardI have to create a program using python so when the user inputs a state, it gives them the info of the capital, state bird, and state rank. Here are the instructions: Your program will initialize lists to store information about the states. You should have one list for the names of the states, one list for the names of the capitals, one list for the names of the state birds per state, and one list for the order number the state joined the union. Alternatively, you can use a db list of lists as demonstrated in the exercises in the book to store the information in one structure or dictionaries. Next ask the user to enter a name of a state. Find the index of that name. Use that index to report back to the user the name of the capital, state bird, and the order the state joined the union.arrow_forward
- In Python, given the list = [10,'Hi',20,'Hello',30,'World',40], use map, lambda, and filter to print the string elements in all upper case. You may use the built-in function upper() only. No other built-in functions are allowed. In another notebook, use reduce, lambda, and filter to sum the integers in the list. Use a single line of code only with the exception of the list definition and the reduce() import.arrow_forwardI have a math assignment using python in jupyter. I am given a list of fruits, as seen below: list = ['apple', 'pear', 'orange', 'banana', 'avocado', 'kiwi', 'mango', 'tomato', 'blueberry', 'apricot', 'peach', 'papaya'] I have to print the second, fourth, sixth, ect. fruit in the list, but I don't know what the correct comand is. I have tried splicing, but I can only get the second and fouth fruit to print.arrow_forwardI have a program that asks for queries. It is based on a CSV file with three columns for a person's name, city, and height. The print statement for City_list gives it a blank. The problem I'm running into is that if I insert a city that isn't in the CSV file, it ends and doesn't transition to other cities. When I do put in the city that is in the list, it prints out the indexes from the file. How can this be revised to ignore off-list cities and work with in-list cities? Example Output: C:\Users\lucas\PycharmProjects\pythonProject3\venv\Scripts\python.exe C:\Users\lucas\Documents\cs1151\ch8\querydata.py Welcome to my query program! What would you like to do? 1) Count how many people in a city: 2) Find the tallest person/people in a city. 0) Quit Option: 1 Which city?Ely The population of Ely is 10 What would you like to do? 1) Count how many people in a city: 2) Find the tallest person/people in a city. 0) Quit Option: 2 Which city?Ely [1, 12, 13, 14, 20, 25, 40, 65, 84, 90]...arrow_forward
- Consider there is a list i.e. listA = {20, 10, 5, 15, 3} Write python code that: a. Creates a function updateListA(), which takes listA as input parameter, adds 30 after 20, and adds 40 at the end of the listA. [Hint: create a parameterized function] b. Creates a function newList(), which takes listA as input parameter and creates a new list newList with same elements as listA but in reverse order. c. If there is a function defined as below: def example(par1, par2=30): print(‘valid’) From the following function calls: i. example(par1=1) ii. example(1, 2) iii. example(par2=1) iv. example(par1=5, par2=6) Which call is valid? Write the values of par1 and par2 if a call is valid? Suggest corrections if a call is invalid.arrow_forwardCreate a square matrix that has ones in the first row and first column, and whose remaining elements are the sum of two elements: the element above and the element to the left. Your program should be able to make a matrix of any size. Do this exercise using a loop (for or while) with break/continue statements as necessary.arrow_forwardI need to write a Java ArrayList program called Search.java that counts the names of people that were interviewed from a standard input stream. The program reads people's names from the standard input stream and from time to time prints a sorted portion of the list of names. All the names in the input are given in the order in which they were found and interviewed. You can imagine a unique timestamp associated with each interview. The names are not necessarily unique (many of the people have the same name). Interspersed in the standard input stream are queries that begin with the question mark character. Queries ask for an alphabetical list of names to be printed to the standard output stream. The list depends only on the names up to that point in the input stream and does include any people's names that appear in the input stream after the query. The list does not contain all the names of the previous interviews, but only a selection of them. A query provides the names of two people,...arrow_forward
- In this task you will work with the linked list of digits we have created in the lessons up to this point. As before you are provided with some code that you should not modify: A structure definition for the storage of each digit's information. A main() function to test your code. The functions createDigit(), append(), printNumber(), freeNumber(), readNumber() and divisibleByThree() (although you may not need to use all of these). Your task is to write a new function changeThrees() which takes as input a pointer that holds the address of the start of a linked list of digits. Your function should change all of those digits in this linked list that equal 3 to the digit 9, and count how many replacements were made. The function should return this number of replacements. Provided codearrow_forwardWritten in python with docstrings if applicable. Thanksarrow_forwardWrite a python program that creates a dictionary containing the U.S. states as keys, and their capitals as values. The program should then randomly quiz the user by displaying the name of a state and asking the user to enter that state's capital. The program should keep a count of the number of correct and incorrect responses. This program has really been giving me trouble. Any help is greatly appreciated. Thanks so much!arrow_forward
- Text book imageDatabase System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationText book imageStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONText book imageDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- Text book imageC How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONText book imageDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningText book imageProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education