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: [1, 0, 0, 0], 1940: [0, 1, 1, 0], 2020: [0, 0, 0, 2]}
    """
    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 tests passed (3 = passes Bechdel)

            if year not in years:
                years[year] = [0, 0, 0, 0]   # initialize
            counts_list = years[year]
            counts_list[score] += 1          # increment count for this score

    return years


def plot_test(years, score):
    """
    Plots the fraction of movies that pass a given number of the Bechdel
    requirements by decade. score = 0 means plot the fraction of movies
    that meet 0 requirements, score = 3 means the movie passes all three
    requirements.
    """
    x_vals = years.keys()
    y_vals = [lst[score] / sum(lst) for lst in years.values()]

    plt.bar(x_vals, y_vals, color='green', width=5)

    plt.title('Fraction of Movies that Pass ' + str(score) + ' Bechdel Requirements')
    plt.ylim([0, 1])
    plt.show()


def main():
    # no need to edit main
    args = sys.argv[1:]
    years = read_file(args[0])
    plot_test(years, int(args[1]))


if __name__ == '__main__':
    main()