Calculating the Maximum, Minimum and Average of Three Numbers
The title says it all. As always, I love to answer those homework questions with obfuscated solutions, for that is unsuitable to hand in those solutions.
A simple way to make a solution to entry-level question like this one harder to understand, is leveraging the fact that functions are first-class in python, so basically logic and I/O operations, almost everything we need here can be stuffed inside a single expression, like this:
[f(n) for f, n in zip((max, min, lambda s: float(sum(s))/len(s)), ([list(map(int, map(raw_input, ':::')))]*3))]
This is the Python 2 version, for Python 3, substitute raw_input
with input
.
It works like so:
>>> [f(n) for f, n in zip((max, min, lambda s: float(sum(s))/len(s)), ([list(map(int, map(raw_input, ':::')))]*3))] :1 :2 :3 [3, 1, 2.0]
For extra fun, I use the number of :
(Colon) to control how many
numbers can be accepted, i.e, for six numbers instead of three, change
':::'
to '::::::'
:
>>> [f(n) for f, n in zip((max, min, lambda s: float(sum(s))/len(s)), ([list(map(int, map(raw_input, '::::::')))]*3))] :12 :34 :56 :78 :90 :42 [90, 12, 52.0]
Because of the incompatible differences between Python 2 and Python 3, it can be a little bit shorter if I am only targeting specific branch of Python.
In Python 2, map
returns a list
, so explicit list
conversion is not needed:
[f(n) for f, n in zip((max, min, lambda s: float(sum(s))/len(s)), ([map(int, map(raw_input, ':::'))]*3))]
On the other hand, division operator returns floating-point numbers by default
in Python 3, float
function call is no longer necessary:
[f(n) for f, n in zip((max, min, lambda s: sum(s)/len(s)), ([list(map(int, map(input, ':::')))]*3))]