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 analy

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

Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 3 steps with 1 images

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

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

 

Solution
Bartleby Expert
SEE SOLUTION
Follow-up Question

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

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

Solution
Bartleby Expert
SEE SOLUTION
Follow-up Question

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)

Solution
Bartleby Expert
SEE SOLUTION
Follow-up Question

How could the program from the original program work without…

  • Lambda
  • Complicated for loops
  • Idx
  • Dictionaries 
Solution
Bartleby Expert
SEE SOLUTION
Follow-up Question

How could this program be done without the lambda function or without "for loops" as complicated as the following?

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.

Solution
Bartleby Expert
SEE SOLUTION
Knowledge Booster
Mergesort
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