답변:
가장 쉬운 방법은 사용하는 것입니다 math.factorial
(Python 2.6 이상에서 사용 가능).
import math
math.factorial(1000)
직접 작성하고 싶은 경우 반복적 인 접근 방식을 사용할 수 있습니다.
def factorial(n):
fact = 1
for num in range(2, n + 1):
fact *= num
return fact
또는 재귀 접근법 :
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
있습니다 계승 기능이 당신이 또한 확인해야합니다, 그래서 오직 양의 정수에 대해 정의 n >= 0
하고 그 isinstance(n, int)
. 그렇지 않은 경우 a ValueError
또는 a를 TypeError
각각 올리십시오 . math.factorial
당신을 위해 이것을 돌볼 것입니다.
Python 2.6 이상에서는 다음을 시도하십시오.
import math
math.factorial(n)
float
함수에 a 를 전달하면 a 가 발생합니다 DeprecationWarning
. 그렇게 n
하려면 int
명시 적으로 다음 math.factorial(int(n))
과 같이 변환해야 합니다. 소수점 이하 자릿수는 버립니다.n.is_integer()
이것은 오래된 스레드이기 때문에 실제로는 필요하지 않습니다. 그러나 여기에 while 루프를 사용하여 정수의 계승을 계산하는 또 다른 방법이 있습니다.
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
가장 짧고 아마도 가장 빠른 해결책은 다음과 같습니다.
from math import factorial
print factorial(1000)
자신 만의 솔루션을 구축 할 수도 있습니다. 일반적으로 두 가지 접근 방식이 있습니다. 나에게 가장 적합한 것은 :
from itertools import imap
def factorial(x):
return reduce(long.__mul__, imap(long, xrange(1, x + 1)))
print factorial(1000)
(결과가 될 때 더 큰 숫자에도 작동합니다 long
)
이를 달성하는 두 번째 방법은 다음과 같습니다.
def factorial(x):
result = 1
for i in xrange(2, x + 1):
result *= i
return result
print factorial(1000)
Python2.5 또는 이전 버전을 사용하는 경우
from operator import mul
def factorial(n):
return reduce(mul, range(1,n+1))
최신 Python의 경우 수학 모듈에 계승이 있으며 여기에 다른 답변이 나와 있습니다.
reduce
으로 Python 3에서 제거되었습니다.
from functools import reduce
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
cProfile.run('fact(126000)')
4 function calls in 5.164 seconds
스택을 사용하는 것은 재귀 호출과 같이 편리하지만 비용이 많이 듭니다. 자세한 정보를 저장하면 많은 메모리를 차지할 수 있습니다.
스택이 높으면 컴퓨터가 함수 호출에 대한 많은 정보를 저장한다는 의미입니다.
이 방법은 반복과 같은 일정한 메모리 만 사용합니다.
def fact(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
cProfile.run('fact(126000)')
4 function calls in 4.708 seconds
def fact(n):
return math.factorial(n)
cProfile.run('fact(126000)')
5 function calls in 0.272 seconds
def factorial(n):
result = 1
i = n * (n -1)
while n >= 1:
result = result * n
n = n - 1
return result
print (factorial(10)) #prints 3628800
여기 내 시도가 있습니다
>>> import math
>>> def factorial_verbose(number):
... for i in range(number):
... yield f'{i + 1} x '
...
>>> res = ''.join([x for x in factorial_verbose(5)])
>>> res = ' '.join([res[:len(res)-3], '=', str(math.factorial(5))])
>>> res
'1 x 2 x 3 x 4 x 5 = 120'
나는 이것이 대답되었다는 것을 알고 있지만 여기에는 역 범위 목록 이해력을 가진 또 다른 방법이있어 범위를 읽기 쉽고 컴팩트하게 만듭니다.
# 1. Ensure input number is an integer by attempting to cast value to int
# 1a. To accomplish, we attempt to cast the input value to int() type and catch the TypeError/ValueError
# if the conversion cannot happen because the value type is incorrect
# 2. Create a list of all numbers from n to 1 to then be multiplied against each other
# using list comprehension and range loop in reverse order from highest number to smallest.
# 3. Use reduce to walk the list of integers and multiply each against the next.
# 3a. Here, reduce will call the registered lambda function for each element in the list.
# Reduce will execute lambda for the first 2 elements in the list, then the product is
# multiplied by the next element in the list, and so-on, until the list ends.
try :
num = int( num )
return reduce( lambda x, y: x * y, [n for n in range(num, 0, -1)] )
except ( TypeError, ValueError ) :
raise InvalidInputException ( "Input must be an integer, greater than 0!" )
이 요지 내에서 코드의 전체 버전을 볼 수 있습니다 : https://gist.github.com/sadmicrowave/d4fbefc124eb69027d7a3131526e8c06
[n for n in range(num, 0, -1)]
, range
이미 반복 가능한 없습니다.
계승n!으로 표시된 양의 정수 n의 은 n보다 작거나 같은 모든 양의 정수의 곱입니다.
공식 :n! = n * (n-1) * (n-2) * (n-3) * (n-4) * ....... * 1
내장 funtion / library 등을 사용하여 파이썬에서 계승을 찾는 방법은 여러 가지가 있습니다. 여기서는 계승의 기본 정의를 참조하여 사용자 정의 함수를 작성했습니다.
def factorial(n):
fact = 1
for i in range(1,n+1):
fact = fact * i
return(fact)
print(factorial(4))
recursive
아래 그림과 같은 기술을 사용하여 계승 함수를 구현할 수도 있습니다. 그러나이 방법은 작은 정수 값에만 효율적입니다. 재귀에서 함수는 반복적으로 호출되며 스택을 유지하기 위해 메모리 공간이 필요합니다. 스택을 유지하기 위해서는 큰 정수 값에 대한 효율적이거나 최적화 된 접근 방식이 아닙니다.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(4))
def factorial(n):
mul = 1
for i in range( 1, n + 1):
mul *= i
print(factorial(6))
아래 코드에서 계승을 계산하려는 숫자를 입력 한 다음 계승 할 계산할 숫자에 1,2, ...., (계승 한 숫자)를 곱합니다. -1을 계산하고 싶습니다)
f = int(input("Enter a number whose factorial you want to calculate = "))#Number
#whose factorial I want to calculate
for i in range(1,f): #assume I have taken f as 5
f=f*i # In 1st iteration f=5*1 => 5 , in second iteration f = 5*2 => 10, 3rd
#iteration f = 10*3 =>30, 4th iteration f = 30*4 =>120
print(f) #It will print the updated value of "f" i.e 120
factorial
내에서 어떻게 사용할 수 있는지 이해하지 못합니다factorial
. 현재 정의하고있는 함수 내에서 같은 함수를 어떻게 사용할 수 있습니까? 저는 Python을 처음 사용하므로 이해하려고합니다.