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}')

Database System Concepts
7th Edition
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Chapter1: Introduction
Section: Chapter Questions
Problem 1PE
icon
Related questions
Question

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}')

Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 5 steps with 3 images

Blurred answer
Follow-up Questions
Read through expert solutions to related follow-up questions below.
Follow-up Question

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))

Solution
Bartleby Expert
SEE SOLUTION
Knowledge Booster
Lists
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Database System Concepts
Computer Science
ISBN:
9780078022159
Author:
Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:
McGraw-Hill Education
Starting Out with Python (4th Edition)
Starting Out with Python (4th Edition)
Computer Science
ISBN:
9780134444321
Author:
Tony Gaddis
Publisher:
PEARSON
Digital Fundamentals (11th Edition)
Digital Fundamentals (11th Edition)
Computer Science
ISBN:
9780132737968
Author:
Thomas L. Floyd
Publisher:
PEARSON
C How to Program (8th Edition)
C How to Program (8th Edition)
Computer Science
ISBN:
9780133976892
Author:
Paul J. Deitel, Harvey Deitel
Publisher:
PEARSON
Database Systems: Design, Implementation, & Manag…
Database Systems: Design, Implementation, & Manag…
Computer Science
ISBN:
9781337627900
Author:
Carlos Coronel, Steven Morris
Publisher:
Cengage Learning
Programmable Logic Controllers
Programmable Logic Controllers
Computer Science
ISBN:
9780073373843
Author:
Frank D. Petruzella
Publisher:
McGraw-Hill Education