Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over lists with a particular sum

I would like to iterate over all lists of length n whose elements sum to 2. How can you do this efficiently? Here is a very inefficient method for n = 10. Ultimately I would like to do this for `n > 25'.

n = 10
for L in itertools.product([-1,1], repeat = n):
    if (sum(L) == 2):
        print L #Do something with L
like image 832
graffe Avatar asked Feb 07 '23 23:02

graffe


1 Answers

you only can have a solution of 2 if you have 2 more +1 than -1 so for n==24

a_solution = [-1,]*11 + [1,]*13  

now you can just use itertools.permutations to get every permutation of this

for L in itertools.permutations(a_solution): print L

it would probably be faster to use itertools.combinations to eliminate duplicates

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

note for you to get 2 the list must be an even length

like image 98
Joran Beasley Avatar answered Feb 13 '23 03:02

Joran Beasley