# CSE 140 13wi Lecture 16 # Design Example # Used to demonstrate the "wishful thinking" approach to creating functions. import matplotlib.pyplot as plt import csv def days_in_month(): """ Returns the number of days in the month to process """ # Stub function # TODO: Write more detailed implementation return 30 def average_delay(rows): """ Given a list of airline delay rows, returns the average delay. """ delays = [] for row in rows: delays.append(float(row["DELAY"])) return sum(delays) / len(delays) def get_delay_vector(rows, days): """ Given a list of rows and days, returns a list containg the average delay on each day. """ output = [] for day in days: day_rows = filter_by_column(rows, "DAY_OF_MONTH", str(day)) output.append(average_delay(day_rows)) return output def filter_by_column(rows, column, value): """ Given a list of rows, a column, and a column value, returns a list of all rows with the given value in the given column. """ filtered_rows = [] for row in rows: if row[column] == value: filtered_rows.append(row) return filtered_rows def plot_airport(rows, airport): """ Given an airport and a list of delay data rows, plots its average delay per day. """ # Filter rows by airport filtered_rows = filter_by_column(rows, "ORIGIN", airport) # Get x vector x_vector = range(1, days_in_month() + 1, 1) # Get y vector y_vector = get_delay_vector(filtered_rows, x_vector) # Plot vectors assert len(x_vector) == len(y_vector) plt.plot(x_vector, y_vector, label=airport) def plot_airports(rows, airports): """ Given a list of airports and airport delay rows, plots the average delay of flights for each airport. """ # Initialize plot plt.xlabel("Day of Month") plt.ylabel("Average Delay (minutes)") plt.title("Average delays at " + str(airports)) # Plot each airport for airport in airports: plot_airport(rows, airport) # Draw the lengend, show plot plt.legend() plt.show() def load_rows(path): """ Returns a list of rows from the CSV file at path. A row is a dictionary that maps a column name (a string) to a value (a string). """ output = [] for row in csv.DictReader(open(path)): output.append(row) return output def get_airports(): """ Returns the airports to process. """ # Stub function # TODO: Write more detailed implementation return ["SEA", "JFK", "DFW", "SFO"] def get_input_path(): """ Returns the path of the input CSV file, containing airport delay data. """ # Stub function # TODO: Write more detailed implementation return "nov.csv" def main(): """ Main program """ # Load rows from CSV file rows = load_rows(get_input_path()) # Get airports to graph airports = get_airports() # Plot the airport delays plot_airports(rows, airports) if __name__ == "__main__": main()