''' DS2000 Spring 2022 Writing and calling functions -- dunkin donuts! In this version, from 2/25, we've added some fun things... - Read from the DD_US.csv file using the csv library. This library is specifically designed for CSV files, so it makes everything a little more simple and elegant. We first import the csv library ("import csv") and then we don't need to use while, true, break, or split to read from a file. - Called a function knowing only its name, params, and return type In class, we scoped out a funciton called read_csv and figure out how to call it (data = read_csv(DD_FILE)) Then we wrote the function too! It uses the CSV library to read in all the dunks locations in the US and return it as a 2d list of strings. - Wrote a function to find the dunks locations in a city. We wrote a function called get_local, which takes in a 2d list of strings, the name of a city, and a col number to look at, and returns a similar but smaller 2d list that is the dunks just in that city - Look how small and easy to follow main is! That's why we love functions! ''' import csv import matplotlib.pyplot as plt DD_FILE = "DD_US.csv" LANEY_LAT = 42.30537 LANEY_LONG = -71.061 LAT_COL = 1 LONG_COL = 0 ADDRESS_COL = 2 def euclidean(x1, y1, x2, y2): ''' Function: euclidean Parameters: four floats, repping two points in the x/y plane Returns: a float, the euclidean distance between the points ''' x_diff = (x2 - x1) ** 2 y_diff = (y2 - y1) ** 2 distance = x_diff + y_diff distance = distance ** .5 return distance def get_lat_long(dd, lat_col, long_col): ''' Function: get_lat_long Parameter: a 1d list, one line from the DD csv file and two ints for lat column and long column Returns: a list of two floats -- the lat/long of a DD location ''' lat = float(dd[lat_col]) long = float(dd[long_col]) lst = [lat, long] return lst def read_csv(filename): ''' Function: read_csv parameter: filename, a string Returns: 2d list of strings, the contents of the file ''' data = [] with open(filename, "r") as infile: csvfile = csv.reader(infile, delimiter = ",") for row in csvfile: data.append(row) return data def get_local(lst, city, col): ''' Function: get_local Parameters: 2d list of strings, a city to look for, and the column where to look for the city Returns: a 2d list of strings, subset of the original but where the city was found ''' locs = [] for row in lst: if city in row[col]: locs.append(row) return locs def main(): # Step one: gather data from the file into a 2d list data = read_csv(DD_FILE) # Step two: computation! # Find all the locations in a city city = input("Enter a city\n") locations = get_local(data, city, ADDRESS_COL) # Step three: communication! # Print out the locations and also plot them on a map print(locations) lats = [] longs = [] for dd in locations: coords = get_lat_long(dd, LAT_COL, LONG_COL) lats.append(coords[0]) longs.append(coords[1]) plt.scatter(longs, lats, color = "orange") main()