Problem 1.5
Mean
Write a function mean
to compute the arthematic mean of a list of numbers.
The arthemetic mean of N
numbers is computed by adding all the N
numbers and dividing the total by N
.
The function takes the list of numbers as argument and returns the mean.
>>> mean([1, 2, 3, 4, 5])
3.0
Solution
def mean(numbers):
return sum(numbers)/len(numbers)
Discussion
The solution is quite straight-forward. We use the built-in function sum
to compute the total and divide it by the number of numbers, which is computed using the built-in function len
.
def mean(numbers):
return sum(numbers) / len(numbers)
You could also write that in multiple lines, if you find that more comfortable.
def mean(numbers):
total = sum(numbers)
n = len(numbers)
return total / n