This exercise is a mix many of the things you have learned in this course - hence it name. So without further ado lets dive into it.
First download datafile.txt linked to here. The file contains a tab-separated table of columns. The fist column are CPR numbers of patients and the remaining columns contain information on each patient.
Exercises
Lists, aliasing and functions
Write a function fillList(listToFill, n) that takes an empty list listToFill as first argument, and an integer n as second argument. The function should not return anything but should fill the list passed to it with integers from 1 to n so that it can be used like this:
L = []
fillList(L, 5)
print L
[1, 2, 3, 4, 5]
Make sure you understand why the following implementation does not work.
def fillList(listToFill, n): listToFill = range(n)
Parse a table into a dictionary
The goal of this exercise is to write a function parsePatientFile(filename) that parses the file filename (use datafile.txt) and returns a dictionary that maps from CPR numbers to tuples of information on the patient with that cpr number. This will let you retrieve the relevant information on patient like this:
Example usage:
patientInfo = parsePatientFile("datafile.txt) print patientInfo["27071972-5337"] ("normal", "non-smoker", 70, 0.68, 51.41, 169.64, 0.79)
Open datafile.txt. Iterate over the lines in the file one by one. Split each line so you can access elements. Use the first element as the key and the remaining list as value.
List comprehensions
Write a list comprehension that generates a list of integers from a list of strings into. E.g. [12, 51, 4] from ["12", "51", "4"].
Write a list comprehension that generates a list of tuples of length larger than two from a list of tuples. E.g. [(1,4,2), (51,63,7,1)] from [(1,4,2), (2,7), (51,63,7,1)].
Classes
Write a class Numbers with methods addNumber and currentSum so that this:
numbers = Numbers()
print numbers.currentSum()
prints
0
and this
numbers = Numbers()
numbers.addNumber(4)
numbers.addNumber(3)
numbers.addNumber(2)
print numbers.currentSum()
prints
9