使用特定总和迭代列表

dor*_*thy 4 python math optimization

我想迭代所有长度列表,n其元素总和为2.你怎么能有效地做到这一点?这是一种非常低效的方法n = 10.最终我想为'n> 25'这样做.

n = 10
for L in itertools.product([-1,1], repeat = n):
    if (sum(L) == 2):
        print L #Do something with L
Run Code Online (Sandbox Code Playgroud)

Jor*_*ley 7

如果你有2个+1而不是-1,你只能得到2的解,所以对于n == 24

a_solution = [-1,]*11 + [1,]*13  
Run Code Online (Sandbox Code Playgroud)

现在你可以使用itertools.permutations来获得它的每一个排列

for L in itertools.permutations(a_solution): print L
Run Code Online (Sandbox Code Playgroud)

使用itertools.combinations来消除重复可能会更快

for indices in itertools.combinations(range(24),11):
    a = numpy.ones(24)
    a[list(indices)] = -1
    print a
Run Code Online (Sandbox Code Playgroud)

注意到你得到2列表必须是一个均匀的长度