遍历具有特定总和的列表 [英] Iterate over lists with a particular sum

查看:62
本文介绍了遍历具有特定总和的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历所有长度为n的列表,它们的元素总和为2.如何有效地做到这一点?这是n = 10的非常低效的方法.最终,我想针对"n> 25"进行此操作.

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

推荐答案

如果您的+1比-1多2,则只能得到2的解,因此对于n == 24

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  

现在您可以只使用itertools.permutations来获取此的每个排列

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

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

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

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

请注意,要获得2,列表的长度必须是偶数

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

这篇关于遍历具有特定总和的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆