In this lab, you are going to practice reading data from files into lists (one and two-dimensional) and then writing some programs which analyze the data. In addition to introduce files, this will give you more practice working with loops and lists.
Exercise 1: Consider the following example from the lecture. Run it and answer the following questions in your notes.
with open("top_male_baby_names_2010s.txt") as male_names_file:
male_names = male_names_file.readlines()
counter = 0
while counter < len(male_names):
male_names[counter] = male_names[counter].rstrip()
counter += 1
print(male_names)
male_names_file?male_names?male_names[counter]? How is this different from male_names[0]? What is the purpose of counter?rstrip()?rstrip() only works on data of a certain type, which one is it?Exercise 2: Given two lists, finiding the items that appear in both lists is a common kind of problem. If we apply it to tthe names lists, we could do this to find out which names were popular as both girls' and boys' names.
The following pseudocode gives the algorithm for printing out any items that are common to two different lists.
Load the files top_male_baby_names_2010s.txt and top_female_baby_names_2010s.txt into lists, then use this algorithm to print out any names that are both a top male name and top female name. If you did it right, you should see that the names Riley and Avery are on both lists.
Exercise 3: Write a program that will determine the average length of names in the top_female_baby_names_2010s.txt file. Hints: you will need to use the len() function to find the length of each name; use an accumulator variable for keeping track of the total length, and then divide by the number of names in the list. If you did it right, you should get an answer of 6.035. If you get something like 7.03, it might mean that you're counting the newline characters, so make sure to strip them out.