Man*_*eep 0 python combinations loops
我有10种货币我正在分析,我想以10%的增量找到这些货币的所有可能组合.例如:
10% of A, 20% of B...etc
Run Code Online (Sandbox Code Playgroud)
约束如下:
总数必须达到100%每种货币的数量可以在0%到100%之间,因此100%A的组合是有效的
目前我的代码看起来像这样:
for element in itertools.product(*curr_arr):
if round(sum(element),1)==1:
comb_input.append(list(element))
Run Code Online (Sandbox Code Playgroud)
其中curr_arr本质上是一个数组,如下所示:
[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
Run Code Online (Sandbox Code Playgroud)
这种方法非常慢,因为它查看所有组合,然后提取总和为1的组合.有没有更有效的方法来做到这一点并加快我的代码?
这很难看,但很快:
combinations = []
for a in xrange(11):
for b in xrange(11-a):
for c in xrange(11-a-b):
for d in xrange(11-a-b-c):
for e in xrange(11-a-b-c-d):
for f in xrange(11-a-b-c-d-e):
for g in xrange(11-a-b-c-d-e-f):
for h in xrange(11-a-b-c-d-e-f-g):
for i in xrange(11-a-b-c-d-e-f-g-h):
j = 10-a-b-c-d-e-f-g-h-i
combinations.append((a,b,c,d,e,f,g,h,i,j))
print len(combinations)
Run Code Online (Sandbox Code Playgroud)
这将在不到0.2秒的时间内为您提供所有92378组合.
请注意,它返回0到10之间的整数值,必须乘以10才能获得百分比.