Programming with Python

Stefan Güttel, guettel.com

Test 4

Notes:

Don't forget to write the programs that allow the examiners to test the functions that you write.

The test programs don't have to catch the exceptions that the functions described in the problems might generate.

Problem 1. Write a function gm(S) that returns the geometric mean of all the elements in an iterable S: $$\left(\prod_{i=1}^n a_i \right)^{1/n} = \sqrt[n]{a_1 a_2 \cdots a_n},$$ where $a_1, a_2, \dots, a_n \ge 0\ $ denote the elements of $S$, and they may be integers and/or floats (you don't have to check, but make sure your program loads them as floats).

If S is empty, the function should raise a ValueError exception with the description "the geometric mean is not defined for an empty set".
If any of the elements of S are negative, the function should raise a ValueError exception with the description "the numbers must be nonnegative".

Hint: The $k$-th root of a number is computed by using a power operator **. However, be careful how you use it, as it takes precedence over other arithmetic operators.

Examples:

  • gm([17, 19, 23]) should return 19.512374350487843 because $\sqrt[3]{17 \cdot 19 \cdot 23} \approx 19.512374350487843$;

  • gm({17, -19, 23}) and gm(list()) should each raise one of the described exceptions.

Problem 2. Write a function that takes a list of strings and returns a tuple of three values (i, f, o), where i is the number of strings in the list that can be converted to a single integer, f is the number of strings in the list that can be converted to a single float but not to an integer, and o is the number of all the other strings in the list.

Hint: To detect which of the three categories a string belongs to, try to convert it into int/float while capturing their ValueError exceptions.

Examples: For a list ["17", " -19.23 ", "", " -13", "11-7", "Happy holidays!"] the function should return (2, 1, 3), because "17" and " -13" can be converted to integers, " -19.23 " can be converted to a float (and not an integer), and "", "11-7", "Happy holidays!" cannot be converted to either of them.

For a list ["0", "0"] the function should return (2, 0, 0), because both "0" can be converted to integers.