숫자 목록 을 가져 와서 곱하는 함수를 작성 해야합니다. 예 :
[1,2,3,4,5,6]
나에게 줄 것이다 1*2*3*4*5*6
. 정말 당신의 도움을 사용할 수 있습니다.
답변
파이썬 3 : 사용 functools.reduce
:
>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
파이썬 2 : 사용 reduce
:
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
2 및 3과 호환되는 pip install six
경우 다음을 사용하십시오 .
>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
답변
당신이 사용할 수있는:
import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)
참조 reduce
및 operator.mul
설명에 대한 문서화.
import functools
파이썬 3 이상 에서 라인 이 필요합니다 .
답변
나는를 사용하는 것이 numpy.prod
작업을 수행 할 수 있습니다. 아래를 참조하십시오.
import numpy as np
mylist = [1, 2, 3, 4, 5, 6]
result = np.prod(np.array(mylist))
답변
가져 오기를 피하고 더 복잡한 Python 영역을 피하려면 간단한 for 루프를 사용할 수 있습니다
product = 1 # Don't use 0 here, otherwise, you'll get zero
# because anything times zero will be zero.
list = [1, 2, 3]
for x in list:
product *= x
답변
시작 Python 3.8
하여 .prod
함수가 math
표준 라이브러리 의 모듈에 포함되었습니다 .
math.prod(iterable, *, start=1)
이 메소드는 start
반복 가능한 숫자 의 값 (기본값 : 1)에 곱을 곱 합니다.
import math
math.prod([1, 2, 3, 4, 5, 6])
>>> 720
iterable이 비어 있으면 1
(또는 start
제공된 경우 값) 생성됩니다.
답변
내 기계의 성능 측정 결과는 다음과 같습니다. 장기 실행 루프에서 작은 입력에 대해 수행되는 경우와 관련이 있습니다.
import functools, operator, timeit
import numpy as np
def multiply_numpy(iterable):
return np.prod(np.array(iterable))
def multiply_functools(iterable):
return functools.reduce(operator.mul, iterable)
def multiply_manual(iterable):
prod = 1
for x in iterable:
prod *= x
return prod
sizesToTest = [5, 10, 100, 1000, 10000, 100000]
for size in sizesToTest:
data = [1] * size
timerNumpy = timeit.Timer(lambda: multiply_numpy(data))
timerFunctools = timeit.Timer(lambda: multiply_functools(data))
timerManual = timeit.Timer(lambda: multiply_manual(data))
repeats = int(5e6 / size)
resultNumpy = timerNumpy.timeit(repeats)
resultFunctools = timerFunctools.timeit(repeats)
resultManual = timerManual.timeit(repeats)
print(f'Input size: {size:>7d} Repeats: {repeats:>8d} Numpy: {resultNumpy:.3f}, Functools: {resultFunctools:.3f}, Manual: {resultManual:.3f}')
결과 :
Input size: 5 Repeats: 1000000 Numpy: 4.670, Functools: 0.586, Manual: 0.459
Input size: 10 Repeats: 500000 Numpy: 2.443, Functools: 0.401, Manual: 0.321
Input size: 100 Repeats: 50000 Numpy: 0.505, Functools: 0.220, Manual: 0.197
Input size: 1000 Repeats: 5000 Numpy: 0.303, Functools: 0.207, Manual: 0.185
Input size: 10000 Repeats: 500 Numpy: 0.265, Functools: 0.194, Manual: 0.187
Input size: 100000 Repeats: 50 Numpy: 0.266, Functools: 0.198, Manual: 0.185
Numpy는 곱셈이 수행되기 전에 배열을 할당하기 때문에 더 작은 입력에서 상당히 느리다는 것을 알 수 있습니다. 또한 Numpy의 오버플로에주의하십시오.
답변
나는 일반 목록의 모든 요소를 함께 곱하는 함수에 대해 개인적으로 이것을 좋아합니다.
def multiply(n):
total = 1
for i in range(0, len(n)):
total *= n[i]
print total
컴팩트하고 간단한 것 (변수 및 for 루프)을 사용하며 직관적입니다. (문제에 대해 생각하고, 하나만 취하고, 곱한 다음 다음에 곱하는 등의 방식으로 보입니다.) )
