Programming with Python

Stefan Güttel,

Test 3

Note: Don't forget to write the programs that allow the examiners to input the data and test the functions that you write. If the function can be called in several different ways, make all of those calls and print their results.

Problem 1. First write a function compare(p1, p2) that performs an element-wise <= comparison of two vectors p1 and p2. Each of the vectors is a string in the format "x, y, ..., z" (a sequence of real numbers (coordinates) separated by a single comma and space combination). If each element of p1 is less than or equal to the corresponding element in p2, the function returns True; otherwise the function returns False. If the two vectors do not belong to the same vector space (they have a different number of coordinates), the function should return None.

Then write a program that loads two vectors in the described format and prints the result of the comparison. If the vectors do not belong to the same vector spaces, print a descriptive error. Other types of invalid input will likely crash your program; this is acceptable and need not be dealt with.

For example,

  • inputs "-13.11, 7.5, -3.2" and "17.19, 23.31, 37.41" should print "p1 is element-wise <= p2",
  • inputs "-13.11, 7.5" and "17.19, 3.31" should print "p1 is not element-wise <= p2",
  • inputs "17.19, 23.31" and "-13.11, 7.5, -3.2" should print "p1 and p2 are not comparable".

Problem 2. Write a function word_freq(s) that takes as input a string s and then prints, line by line, each of the words contained in s and the number of occurences, with the words listed in alphabetical order. Words in s are separated by spaces and the function should not make a distinction between words being capitalized or not. Furthermore, commas (,) and full stops (.) should be ignored.

Example output:

In [26]:
word_freq("The University of Manchester is the best university, in the world.")
best       1
in         1
is         1
manchester 1
of         1
the        3
university 2
world      1

The indentation should be such that the numbers are aligned and there is enough space for the longest word to be printed. Make sure your function does not print anything when the string s does not contain words, like for example s='... ...'.