일부 고정 된 리소스 (예 : n=10
)를 일부 지역 (예 : t=5
)에 할당하려고한다고 가정 해 보겠습니다. 나는 합계가 n
또는 그 이하인 모든 조합을 얻는 방법을 효율적으로 알아 내려고 노력 중이다.파이썬에서 합계가 10 이하인 모든 조합을 효과적으로 얻는 방법
예. 이 좋고, 0,0,5,5,0
등이 있고, 3,3,3,3,3,3
은 분명히 틀립니다.
import itertools
t = 5
n = 10
r = [range(n+1)] * t
for x in itertools.product(*r):
if sum(x) <= n:
print x
이 무력 접근 방식은 비록 매우 느린; 더 좋은 방법이 있어야합니까?
타이밍 (1000 반복) :
Default (itertools.product) --- time: 40.90 s
falsetru recursion --- time: 3.63 s
Aaron Williams Algorithm (impl, Tony) --- time: 0.37 s
숫자의 모든 합계 조합을 찾고 싶습니까? – GLHF
@qqvc 맞나요? – PascalVKooten
[this one]의 가능한 복제본 (http://stackoverflow.com/questions/14162798/generating-all-distinct-partitions-of-a-number)? 여기에있는 작업은 모든 [정수의 파티션] (http://en.wikipedia.org/wiki/Partition_%28number_theory%29)을 찾는 것입니다. – Tony