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, dictionaries, named functions, or the key or lambda function to sort it. What are some ways I could code for this?
import csv
data = []
with open("C:\\Users\\lucas\\Downloads\\sample-data.csv") as f:
reader = csv.reader(f)
for row in csv.reader(f):
data.append(list(row))
f.close()
data.pop(0)
# print(data)
city_list = []
city = row[1]
for i in range(len(data)):
city_list.append(data[i][1])
city_list.sort()
print(city_list)
unique_cities = []
people_count = []
for city in city_list:
# this if statement analyzes which cities are in unique_cities. If they are not in the list,
# then they will be appended into the list
if city not in unique_cities:
unique_cities.append(city)
for city in unique_cities:
# because unique cities lists one of each city,
# and because we want to count the frequency of the cities, we use city_list
count = city_list.count(city)
people_count.append(count)
print(unique_cities)
print(people_count)
height_list = []
for d in data:
if city == d[1]:
height_list.append(float(d[2]))
avg = sum(height_list)/len(height_list)
Trending nowThis is a popular solution!
Step by stepSolved in 3 steps with 1 images
How could this program work without items() or enumerate?
def Find_heights(data):
heights = []
for d in data:
city = d[1]
height = float(d[2])
index = -1
for i, item in enumerate(heights):
if item[0] == city:
index = i
break
if index == -1:
heights.append([city, [height]])
else:
heights[index][1].append(height)
return heights
height_list = Find_heights(csv_data)
print(height_list)
# Output: [['New York', [5.8, 5.9, 6.0]], ['Los Angeles', [5.5, 5.6, 5.7]], ['Chicago', [5.9, 6.0, 6.1]], ['Houston', [5.6, 5.7, 5.8]]]
#To remove the items from the Find_average function, you can modify it to return a dictionary with city names as keys and average heights as values. Here's an updated version of the function:
def Find_average(heights_list):
averages = {}
for city_data in heights_list:
city = city_data[0]
heights = city_data[1]
average = sum(heights) / len(heights)
averages[city] = average
return averages
How could this code work with...
- lists instead of dictionaries?
- without the items as in...
- def Find_average(heights_dict):
for city, heights in heights_dict.items():
average = sum(heights) / len(heights)
print(f"{city}: {average}")
- def Find_average(heights_dict):
-
import csvcsv_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 d in data:
city = d[1]
height = float(d[2])
if city not in heights:
heights[city] = [height]
else:
heights[city].append(height)
return heights
height_list = Find_heights(csv_data)
print(height_list)
def Find_averages(heights):
for city, heights in heights:
for averages in heights:
averages = sum(heights)/ len(heights)
return averages
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)
print(name_list)
def Find_indexes(unique_city, data_set):
index_list = []
index = 0
for row in data_set:
if row[1] == unique_city:
index_list.append(index)
index += 1
return index_list
indexes = Find_indexes(unique_cities, csv_data)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_diffdifference_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}')
print(city, avg, difference_list)
print(height_list)
I am trying to do something similar with the code below. I'm trying to find the average height of each city, but it only prints out one average. Can someone tell me where the problem is?
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(float(d[2]))
return heights
height_list = Find_heights(csv_data)
print(height_list)
def Find_average(heights):
local_averages = []
average = sum(heights) / len(heights)
for average in heights:
local_averages.append(average)
return average
avg = Find_average(height_list)
print(avg)
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)
print(name_list)
def Find_indexes(unique_city, data_set):
index_list = []
index = 0
for row in data_set:
if row[1] == unique_city:
index_list.append(index)
index += 1
return index_list
indexes = Find_indexes(unique_cities, csv_data)
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}')
print(city, avg, difference_list)
print(height_list)
How could the
- Lambda
- Complicated for loops
- Idx
- Dictionaries
How could this
for city in city_data:
heights = city_data[city]
avg_height = sum(heights) / len(heights)
diff_list = [abs(height - avg_height) for height in heights]
city_diff[city] = diff_list
Also, the program needs to find two people from each city.
How could this program work without items() or enumerate?
def Find_heights(data):
heights = []
for d in data:
city = d[1]
height = float(d[2])
index = -1
for i, item in enumerate(heights):
if item[0] == city:
index = i
break
if index == -1:
heights.append([city, [height]])
else:
heights[index][1].append(height)
return heights
height_list = Find_heights(csv_data)
print(height_list)
# Output: [['New York', [5.8, 5.9, 6.0]], ['Los Angeles', [5.5, 5.6, 5.7]], ['Chicago', [5.9, 6.0, 6.1]], ['Houston', [5.6, 5.7, 5.8]]]
#To remove the items from the Find_average function, you can modify it to return a dictionary with city names as keys and average heights as values. Here's an updated version of the function:
def Find_average(heights_list):
averages = {}
for city_data in heights_list:
city = city_data[0]
heights = city_data[1]
average = sum(heights) / len(heights)
averages[city] = average
return averages
How could this code work with...
- lists instead of dictionaries?
- without the items as in...
- def Find_average(heights_dict):
for city, heights in heights_dict.items():
average = sum(heights) / len(heights)
print(f"{city}: {average}")
- def Find_average(heights_dict):
-
import csvcsv_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 d in data:
city = d[1]
height = float(d[2])
if city not in heights:
heights[city] = [height]
else:
heights[city].append(height)
return heights
height_list = Find_heights(csv_data)
print(height_list)
def Find_averages(heights):
for city, heights in heights:
for averages in heights:
averages = sum(heights)/ len(heights)
return averages
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)
print(name_list)
def Find_indexes(unique_city, data_set):
index_list = []
index = 0
for row in data_set:
if row[1] == unique_city:
index_list.append(index)
index += 1
return index_list
indexes = Find_indexes(unique_cities, csv_data)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_diffdifference_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}')
print(city, avg, difference_list)
print(height_list)
I am trying to do something similar with the code below. I'm trying to find the average height of each city, but it only prints out one average. Can someone tell me where the problem is?
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(float(d[2]))
return heights
height_list = Find_heights(csv_data)
print(height_list)
def Find_average(heights):
local_averages = []
average = sum(heights) / len(heights)
for average in heights:
local_averages.append(average)
return average
avg = Find_average(height_list)
print(avg)
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)
print(name_list)
def Find_indexes(unique_city, data_set):
index_list = []
index = 0
for row in data_set:
if row[1] == unique_city:
index_list.append(index)
index += 1
return index_list
indexes = Find_indexes(unique_cities, csv_data)
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}')
print(city, avg, difference_list)
print(height_list)
How could the
- Lambda
- Complicated for loops
- Idx
- Dictionaries
How could this
for city in city_data:
heights = city_data[city]
avg_height = sum(heights) / len(heights)
diff_list = [abs(height - avg_height) for height in heights]
city_diff[city] = diff_list
Also, the program needs to find two people from each city.
- In python don't import librariesarrow_forwardIn 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_forward
- Write 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_forwardIn pythonWrite a function called compter_les_votes that accepts a list of ballots as input (of arbitrary length) and produces a report as a dictionary. The ballots have the form of a couple (valid, condidat) where candidate is the name of one of the candidates in the election, and valid is a boolean that indicates whether or not the ballot is valid. For example, for the following list of bulletins: [(True, 'Pierre'), (False, 'Jean'), (True, 'Pierre'), (True, 'Jacques')]Your function must return the following dictionary: { "number of ballots": 4, "invalid ballots": 1, "results": { "Stone": 2, "Jacques": 1 }}Note that you do not have to display the dictionary, only return it.arrow_forwardYou are going to write a program (In Python) called BankApp to simulate a banking application.The information needed for this project are stored in a text file. Those are:usernames, passwords, and balances.Your program should read username, passwords, and balances for each customer, andstore them into three lists.userName (string), passWord(string), balances(float)The txt file with information is provided as UserInformtion.txtExample: This will demonstrate if file only contains information of 3 customers. Youcould add more users into the file.userName passWord Balance========================Mike sorat1237# 350Jane para432@4 400Steve asora8731% 500 When a user runs your program, it should ask for the username and passwordfirst. Check if the user matches a customer in the bank with the informationprovided. Remember username and password should be case sensitive.After asking for the user name, and password display a menu with the...arrow_forward
- Write a python program that reads the contents of a text file. The program should create a dictionary in which the keys are the individual words found in the file and the values are the number of times each word appears. For example, if the word "the" appears 128 times, the dictionary would contain an element with 'the' as the key and 128 as the value. The program should either display the frequency of each word or create a second file containing a list of each word and it's frequency. This program has really been giving me trouble. Any help is great appreciated. Thanks so much!arrow_forwardPYTHON Complete the function below, which takes two arguments: data: a list of tweets search_words: a list of search phrases The function should, for each tweet in data, check whether that tweet uses any of the words in the list search_words. If it does, we keep the tweet. If it does not, we ignore the tweet. data = ['ZOOM earnings for Q1 are up 5%', 'Subscriptions at ZOOM have risen to all-time highs, boosting sales', "Got a new Mazda, ZOOM ZOOM Y'ALL!", 'I hate getting up at 8am FOR A STUPID ZOOM MEETING', 'ZOOM execs hint at a decline in earnings following a capital expansion program'] Hint: Consider the example_function below. It takes a list of numbers in numbers and keeps only those that appear in search_numbers. def example_function(numbers, search_numbers): keep = [] for number in numbers: if number in search_numbers(): keep.append(number) return keep def search_words(data, search_words):arrow_forwardIn python: student_dict is a dictionary with students' name and pedometer reading pairs. A new student is read from input and added into student_dict. For each student in student_dict, output the student's name, followed by "'s pedometer reading: ", and the student's pedometer reading. Then, assign average_value with the average of all the pedometer readings in student_dict..arrow_forward
- IN PYTHON PLEASE Write a function def sameSet(a, b) that checks whether two lists have the same ele- ments in some order, ignoring duplicates. For example, the two lists 149 16 9 7 4 9 11 and 11 11 7 9 16 4 1 would be considered identical. You will probably need one or more helper functions.arrow_forwardIn Python, how do we sort a dictionary by values, without importing any additional modules? You should only use one line of code here, and you must use the function zip. Please explain how the code is working as well: d = {'a':11,'e':2,'v':32,'c':4}arrow_forwardin this assignment i have to remove vowels from a string using a linked list. the linked list and link code is from a textbook and cannot be changed if the code alters the data structure. for some reason when i implement this code it gives me a logical error where the program only removes all instances of the first vowel in a string instead of moving through all vowels of the string and removing each one with all instances. i would appreciate if you could tell me the problem and solution in words and not in code. The code is in java. output please enter a string.researchhcraeserfalseList (first -->last): researchList (first -->last): researchList (first -->last): rsarch CODE MAIN FUNCTION import java.util.Scanner;/*** Write a description of class test here.** @author (your name)* @version (a version number or a date)*/public class test{// instance variables - replace the example below with your ownpublic static void main(String[] args){Scanner input = new...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