Section 8 Solutions


Written by Erin McCoy, Juliette Woodrow, and 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]
      
    

Bechdel and Other Tests

                
import sys
import matplotlib.pyplot as plt

FILENAME = 'data/next_bechdel_tests.txt'
TESTS = ['Bechdel', 'Peirce', 'Landau','Feldman','Villarreal', 'Hagen', 'Ko', 'Villalobos','Waithe', 'Koeze-Dottle','Uphold','White', 'Rees-Davies' ]


def read_file(filename):
    """
    Reads the information from the specified file and builds a new
    movie_data dictionary with the data found in the file. Returns the
    newly created dictionary.
    """
    movie_data = {}
    with open(filename) as f:
        lines = f.readlines()
        for line in lines[1:]:
            items = line.split(',')
            movie = items[0]
            tests = items[1:]
            tests = [int(test) for test in tests]
            movie_data[movie] = tests
    return movie_data


def plot_test(movie_data, test_name):
    test_index = TESTS.index(test_name)
    num_passed = 0
    num_failed = 0

    # your code here to count number of movies that pass and fail this test
    for movie in movie_data:
        inner = movie_data[movie]
        test_score = inner[test_index]
        if test_score == 1:
            num_failed += 1
        else:
            num_passed += 1

    # your code here to plot the data
    x_vals = ['Passed', 'Failed']
    y_vals = [num_passed, num_failed]
    plt.bar(x_vals, y_vals, color='green')

    plt.ylabel('Number of Movies')
    plt.title(test_name + ' Test Plots')

    plt.ylim([0, 50])
    plt.show()

    
def main():
    # no need to edit main
    args = sys.argv[1:]
    movie_data = read_file(FILENAME)
    if args[0] == '-dict':
        print(movie_data)
    if args[0] == '-test':
        plot_test(movie_data, args[1])


if __name__ == '__main__':
    main()