Repository navigation
Expand file tree
/
Copy pathcityreader.py
More file actions
78 lines (67 loc) · 2.56 KB
/
Copy pathcityreader.py
File metadata and controls
78 lines (67 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import csv
# Create a class to hold a city location. Call the class "City". It should have
# fields for name, latitude, and longitude.
class City():
def __init__(self,name, lat, lon):
self.name = name
self.lat = float(lat)
self.lon = float(lon)
# We have a collection of US cities with population over 750,000 stored in the
# file "cities.csv". (CSV stands for "comma-separated values".)
#
# Use Python's built-in "csv" module to read this file so that each record is
# imported into a City instance. (You're free to add more attributes to the City
# class if you wish, but this is not necessary.) Google "python 3 csv" for
# references and use your Google-fu for other examples.
#
# Store the instances in the "cities" list, below.
#
# Note that the first line of the CSV is header that describes the fields--this
# should not be loaded into a City object.
cities = []
with open('cities.csv', newline='') as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
cities.append(City(row[0], row[3], row[4]))
# Print the list of cities (name, lat, lon), 1 record per line.
for c in cities:
print(f"{c.name}, {c.lat}, {c.lon}")
# *** STRETCH GOAL! ***
#
# Allow the user to input two points, each specified by latitude and longitude.
# These points form the corners of a lat/lon square. Output the cities that fall
# within this square.
#
# Be aware that the user could specify either a lower-left/upper-right pair of
# coordinates, or an upper-left/lower-right pair of coordinates. Hint: normalize
# the input data so that it's always one or the other, then search for cities.
#
# Example I/O:
#
# Enter lat1,lon1: 45,-100
# Enter lat2,lon2: 32,-120
# Albuquerque: (35.1055,-106.6476)
# Riverside: (33.9382,-117.3949)
# San Diego: (32.8312,-117.1225)
# Los Angeles: (34.114,-118.4068)
# Las Vegas: (36.2288,-115.2603)
# Denver: (39.7621,-104.8759)
# Phoenix: (33.5722,-112.0891)
# Tucson: (32.1558,-110.8777)
# Salt Lake City: (40.7774,-111.9301)
ul_lat_lon = input("\n\nEnter the Upper Left lat,lon: ").split(",")
lr_lat_lon = input("\nEnter the Lower Right lat,lon: ").split(",")
lat1 = float(ul_lat_lon[0])
lon1 = float(ul_lat_lon[1])
lat2 = float(lr_lat_lon[0])
lon2 = float(lr_lat_lon[1])
cities_in_square = [f"{c.name}: ({c.lat},{c.lon})" for c in cities
if (c.lat >= lat1 and c.lat <= lat2
and c.lon >= lon1 and c.lon <= lon2) ]
print("\n\nCities in square:")
for cs in cities_in_square:
if len(cs) == 0:
print('sorry no cities found in that square')
else:
print(cs)