MIT 6.0002 Introduction to Computational Thinking and Data Science, Fall 2016 · Problem set 1, Problem A.1: Loading Cow Data — load_cows · Prof. Eric Grimson, Prof. John Guttag and Dr. Ana Bell · CC BY-NC-SA 4.0 · MIT publishes no solution for this set; the worked solution is ours
Implement the function load_cows(filename). It should take in the name of the data text file as a string, read in its contents, and return a dictionary that maps cow names to their weights.
The aliens want to take home their mutant cows, which jump over the moon. Their spaceship has a weight limit, and somehow they have bred cows with only integer weights. The data for the cows to be transported is stored in ps1_cow_data.txt, and another set of cows for another separate transport is in ps1_cow_data_2.txt — two files for you to read from and test individually. (MIT also encourages you to write your own cow list files for testing; your function should work on any file in this format.)
You can expect the data to be formatted in pairs of x,y on each line, where x is the name of the cow and y is a number indicating how much the cow weighs in tons. Here are the first few lines of ps1_cow_data.txt:
Maggie,3 Herman,7 Betsy,9 ...
You can assume that all the cows have unique names. The weights in the returned dictionary are integers, not strings.
Some functions that may be helpful: str.split, open, file.readline, file.close.
print(load_cows('ps1_cow_data.txt')['Maggie']) # 3 print(load_cows('ps1_cow_data.txt')['Herman']) # 7 print(load_cows('ps1_cow_data.txt')['Betsy']) # 9 print(len(load_cows('ps1_cow_data.txt'))) # 10
Adapted for the browser: both of MIT's data files are written into the working directory before your code runs, so open('ps1_cow_data.txt') works as it would next to ps1a.py.