...

/

Solution Review: Square the Factorials

Solution Review: Square the Factorials

The solution to the 'Square the Factorials' challenge.

We'll cover the following...
Press + to interact
Python 3.10.4
def factorial(n):
if n == 1 or n == 0:
return 1
else:
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 first n numbers. The map function applies the factorial function to every member of an iterable (0… n-1) calculated with the range() function, and returns the result. The result for every member is stored in a list using the list() function. Now we can call the lambda function on each member of this list to calculate the squares. The part for x will pick each factorial from here one by one.

  • The part (lambda a : a*a)(x) will calculate the squares. This anonymous function takes a as a parameter and returns a*a (the square of the number). As discussed above, x will hold each factorial turn by turn, so this anonymous function is called on x in 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.


Ask