Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Third solution in Clear category for Number With Exclamation by mu_py
from functools import reduce
# reduce() applies a function (1st argument) cumulatively to the items of an iterable (2nd argument)
# see https://docs.python.org/3/library/functools.html#functools.reduce
def factorial(n: int) -> int:
""" return the factorial of a non-negative integer """
# we have to take care of special case 0!=1
numbers = range(1, n+1) if n else [1]
# any function that multiplies 2 numbers,
# see mision "multiply-intro"
mult_two = lambda a, b: a * b
return reduce(mult_two, numbers)
# of course it's a bit "too much" to use reduce() here
# however, this seems to be a good chance to showcase this function
print("Example:")
print(factorial(4))
# These "asserts" are used for self-checking
assert factorial(0) == 1
assert factorial(1) == 1
assert factorial(5) == 120
assert factorial(10) == 3628800
assert factorial(15) == 1307674368000
print("The mission is done! Click 'Check Solution' to earn rewards!")
Oct. 16, 2024