Section 8 Solutions


Written by Elyse Cornwall

List Comprehensions

Temps, Revisited

    
temps_f = [45.7, 55.3, 62.1, 75.4, 32.0, 0.0, 100.0]  # given

temps_c = [(temp - 32) * 5 / 9 for temp in temps_f]


Movie Tuples

    
movies = [('alien', 8, 1), ('titanic', 6, 9), ('parasite', 10, 6), ('caddyshack', 4, 5)]  # given

# Produce a list of the second elements (overall scores) of each tuple.
overall_scores = [movie[1] for movie in movies]

# Produce a list of the sum of the second and third elements (overall score plus date score) of each tuple.
sum_scores = [movie[1] + movie[2] for movie in movies]

# Produce a list of the first elements (movie name) of each tuple, except that the first character of each name is made uppercase.
uppercase_names = [movie[0][0].upper() + movie[0][1:] for movie in movies]
      
    

Comprehending Bechdel


import sys
import matplotlib.pyplot as plt


def read_file(filename):
    """
    (Provided)
    Reads the information from the specified file and builds a new
    years dictionary with the data found in the file. Returns the
    newly created dictionary.
    >>> read_file('data-short.txt')
    {1900: [0, 1], 1940: [0, 2], 2020: [2, 0]}
    """
    years = {}
    with open(filename) as f:
        for line in f:
            line = line.strip()
            parts = line.split(',')

            year = int(parts[2]) // 10 * 10  # round year down to nearest decade
            score = int(parts[1])            # number of Bechdel requirements met

            if year not in years:
                years[year] = [0, 0]         # initialize (pass, fail) counts to 0
            counts_tup = years[year]
            if score == 3:                   # if this movie passes all 3 Bechdel requirements
                counts_tup[0] += 1
            else:
                counts_tup[1] += 1
    return years


def plot_test(years):
    """
    Plots the fraction of movies that pass the Bechdel test over time.
    Years is a nested dictionary where the keys are decades as ints,
    and values are lists where index 0 has the number of tests that
    passed and index 1 has the number of tests that failed.
    """
    x_vals = years.keys()
    # y_vals = [lst[0] for lst in years.values()] <- number milestone
    y_vals = [lst[0]/sum(lst) for lst in years.values()]

    plt.plot(x_vals, y_vals, color='green')

    plt.title('Number of Movies that Pass the Bechdel Test')
    plt.show()


def main():
    # no need to edit main
    args = sys.argv[1:]
    if len(args) == 1:
        years = read_file(args[0])
        plot_test(years)
    else:
        print('Usage: python3 bechdel-graphs.py [filename]')


if __name__ == '__main__':
    main()