Sum of the Squares of the first 5 numbers Link to heading
In this post I will try to use the map()
and reduce()
functions to compute the sum of the squares of the first five numbers. The map()
function takes a function and an iterable as a parameter. The items of the iterable are fed to the function to create a new list. The reduce()
function also takes a function and an iterable as a parameter. However, this takes two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.
So, the first 5 numbers are 1, 2, 3, 4, 5. And, the first task would be to find the the squares of each of these numbers. Lets start with writing a simple function that finds the square of a number.
def sqr(x):
return x*x
Now, that we know how to find the squares, lets write a function that can find the sum of two numbers.
def sum(x,y):
return x+y
We can get the first 5 numbers using the range()
function into a list. The next step would be to find the square of each numbers. This can be achieved by passing each of the elements from the list into the sqr()
function using python’s built-in map()
function.
a = range(1,6)
squares = map(sqr, a)
Once, we have the the squares in a list, we would now want to add each of these items to find the sum of the squares.
sum_of_squares = reduce(sum, squares)
The full program listing
a = range(1,6)
def sqr(x):
return x*x
def sum(x,y):
return x+y
squares = map(sqr, a)
sum_of_squares = reduce(sum, squares)