반응형
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example: 5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the value of 0! is 1.
Write a function to calculate factorial for a given input. If input is below 0 or above 12 throw an exception of type ArgumentOutOfRangeException (C#) or IllegalArgumentException (Java) or RangeException (PHP) or throw a RangeError (JavaScript) or ValueError (Python) or return -1 (C).
More details about factorial can be found here.
Solution:
import math
def factorial(n):
if n < 0 or n > 12:
raise ValueError
return math.prod(list(range(1, n+1))) or 1
math.prod multiplies the elements of an array.
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Find the unique number (0) | 2022.08.08 |
---|---|
Fix string case (2) | 2022.08.07 |
Count the Digit (0) | 2022.08.05 |
Descending Order (0) | 2022.08.05 |
Small enough? - Beginner (0) | 2022.08.03 |