Starting from:
$30

$24

Exercise #5 Solution

This week's exercise will revolve around reading les. Since you don't know the names or locations of the les, we will open/close them for you, and just pass in the file handle to your functions. As usual, your functions should all be in a le called ex5.py, that doesn't use input, import or print. Since you really have no way of using our .test les to test le I/O, you don't need to submit your testing les. But that doesn't mean you shouldn't be testing, just that we won't be evaluating your testing this time.




Finding Function Names




Write a function called function names that takes as a parameter a le handle open for reading, and returns a list1 of all of the function names in that le. Remember that function de nitions have a very speci c format: def function name(parameters). You can assume that all functions are exactly correctly formatted according to PEP-8 standards. e.g., 1 space after the def, no space before the (.







Calling function names on ex4.py would (hopefully) return the result:










[ insert , up_to_first , cut_list ]




Hint: look through the str methods, some of them will be quite helpful, such as startswith or find




Justi ed




Write a function called justified that takes as a parameter a le handle open for reading, and returns a boolean which is true if and only if every line in that le is left-justi ed (the rst character is something other than a space2). If any lines start with a space, the program should return False.




Challenge: Ensure that your code works e ciently on a very long le with one of the rst lines being non-left-justi ed




Bonus: Section Average




Write a function called section average3 that takes two parameters: The rst parameter is an open le of midterm marks (no, they're not real marks). Each line represents a single student and consists of a student number, a name, a section code and a midterm grade, all separated by whitespace. An example le has been uploaded as ex5 grade file.txt. The second parameter is a section code. Return the average midterm mark for all students in that section, or return None if the section code does not appear in the marks le for any students. As before, this will be run through the auto-marker, but the marks won't count. It's just for your own enjoyment.







Hint: the split method might be particularly useful here.




Hint: Notice that not everyone has the same number of names, so we can't just assume that the mark and section code will be at a particular index... at least not reading from the left.

























The type contract for this would be (io.TextIOWrapper) - list of str



2blank lines count as left justi ed

3As with previous bonus questions, this question will be marked for your own information, but your nal mark for the

exercise will be solely decided by the previous 2 questions.




1

More products