Solution Review: Square the Factorials
The solution to the 'Square the Factorials' challenge.
We'll cover the following...
def factorial(n):if n == 1 or n == 0:return 1else:return n*factorial(n-1)def square_factorial(n):return [(lambda a : a*a)(x) for x in (list(map(factorial, range(n))))]print(square_factorial(6))
Explanation
In the code above, according to the problem statement, there are two parts: the factorial and the square_factorial function. Let us first go through the factorial function.
Look at the function’s header at line 1. It takes a parameter n. We are using the recursive approach to compute the factorial of the number n. The recursion will not be explained, as it is not our concern here.
Now, look at the main part of the solution: the square_factorial function. According to its definition (at line 7), it takes a parameter n. It is used to calculate the squares of the factorials of the first n numbers (from 0 to n-1). The challenge was to write a single-line implementation. The following expression solves it:
return [(lambda a : a*a)(x) for x in (list(map(factorial, range(n))))]
Let us break it down, to understand what we did.
-
The part
for x in (list(map(factorial, range(n))))calculates the factorial of the firstnnumbers. Themapfunction applies thefactorialfunction to every member of an iterable (0…n-1) calculated with therange()function, and returns the result. The result for every member is stored in a list using thelist()function. Now we can call thelambdafunction on each member of this list to calculate the squares. The partfor xwill pick each factorial from here one by one. -
The part
(lambda a : a*a)(x)will calculate the squares. This anonymous function takesaas a parameter and returnsa*a(the square of the number). As discussed above,xwill hold each factorial turn by turn, so this anonymous function is called onxin every iteration. We are storing the squares in a list. In the end, the list is returned.
Look at line 10. We are calling square_factorial for the first 6 numbers: 0, 1, 2, 3, 4, and 5. The part (list(map(factorial, range(n)))) will generate [1, 1, 2, 6, 24, 120]. Then (lambda a : a*a)(x) for x in [1, 1, 2, 6, 24, 120] will create [1, 1, 4, 36, 576, 14400] which is the final result.