简体   繁体   English

python获取长度为X的列表,其中所有值的总和为Y

[英]python get a list of length X where the sum of all values is Y

I need to find all the combinations of lists who has their sum equal to X in the shortest possible time. 我需要找到在最短时间内总和等于X的所有列表组合。

At this moment i have this: 目前,我有这个:

def deduceArrayFromSum(arr, expectedSum, depth, maxDepth, intervalEnd, intervalStart):
    if maxDepth<=maxOffset:
        if expectedSum>0:
            i = min(intervalEnd, asum)
            while i>=intervalStart:
                if expectedSum>=i and depth<maxOffset:
                    arr[depth] = i
                    deduceArrayFromSum(arr, expectedSum-i, depth+1, maxDepth, i, intervalStart)
                i=i-1
        elif asum==0:
            foundSum(arr)

For every combination found, it calls foundSum() 对于找到的每个组合,它将调用foundSum()

I would expect that i could optimize this by making it linear instead of recursive calls, and by avoiding sending the arr variable at every call. 我希望我可以通过使其线性而不是递归调用来优化此方法,并避免在每次调用时都发送arr变量。 Another possible way to speed this up would be by using yield , but I cannot seem to understand how it works. 加快速度的另一种可能方法是使用yield ,但是我似乎无法理解它是如何工作的。

Maybe numpy can help somehow? 也许numpy可以以某种方式提供帮助?


Edit: arr starts as [0, 0, 0] when calling deduceArrayFromSum(arr, 100, 0, len(arr), 100, 0) , foundSum() gets called with the following params: 编辑:当调用deduceArrayFromSum(arr, 100, 0, len(arr), 100, 0) )时,arr以[0,0,0]开始,使用以下参数调用foundSum()

[100, 0, 0]
[99, 1, 0]
[98, 2, 0]
[98, 1, 1]
[...]

I hope this clears what i want from this code 我希望这可以清除我想要的这段代码

Use itertools.combinations . 使用itertools.combinations

import itertools

def deduceArrayFromSum(arr, length, expectedSum):
    for combination in itertools.combinations(arr, length):
        if sum(combination) == expectedSum:
            foundSum(combination)

With a little refactoring, I would turn it into a generator: 经过一点重构,我将其变成一个生成器:

import itertools

def combinations_with_sum(iterable, length, sum_):
    return (c in itertools.combinations(iterable, length) if sum(c) == sum_)

Then you could use it like this: 然后,您可以像这样使用它:

for t in combinations_with_sum([1, 2, 3, 4], 2, 5):
    print t

or 要么

print list(combinations_with_sum([1, 2, 3, 4], 2, 5))

This problem is NP-complete , so it will always be slow for large inputs. 这个问题是NP完全的 ,因此对于大的输入它总是很慢。 But you may consider researching better algorithms than brute force. 但是您可能会考虑研究比蛮力更好的算法。

You can do this: 你可以这样做:

>>> from itertools import combinations_with_replacement as it_cr
>>> len_=3
>>> tgt=100
>>> li=[t[::-1] for t in it_cr(range(tgt+1), len_) if sum(t)==tgt]
>>> li
[(100, 0, 0), (99, 1, 0), (98, 2, 0), (97, 3, 0), (96, 4, 0), (95, 5, 0),
...
 (35, 33, 32), (34, 34, 32), (34, 33, 33)]

Which is easily turned into a generator: 很容易变成发电机:

def tups_sum_x(tgt, len_):
    for t in it_cr(range(tgt+1), len_):
        if sum(t)==tgt:
            yield t[::-1]

If you want the same order that you present, just sort: 如果您想要与您提供的订单相同的商品,只需排序:

>>> sorted(li, key=lambda t: (-t[0], t[1:]))
[(100, 0, 0), (99, 1, 0), (98, 1, 1), (98, 2, 0), (97, 2, 1), (97, 3, 0), ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 试图获取列表列表中最大 y 值的总和([[x,y],[x,y]......) - Trying to get the sum of the max y values in a list of lists ( [[x,y],[x,y]......) 对于NxM数组,编写一个函数,使其在用户输入为(x,y)时应返回从(0,0)到(x,y)的所有值的总和。 其中x - For NxM array , Write a function such that if user input is (x,y) It should return a sum of all values from (0,0) to (x,y). where x<N & y<M Python中从X到Y的所有函数的列表 - A list of all functions from X to Y in Python PYTHON:解决 y=a+b*x 其中 x 是预定义列表 - PYTHON: solving y=a+b*x where x is a predefined list 使用python中的while循环求和所有可被y整除的0到x的数字 - Sum all numbers 0 to x that are divisible by y using while loop in python python sum(list)和reduce(lambda x,y:x + y,list)之间有差异吗? - Discrepancy between python sum(list) and reduce(lambda x, y : x+y, list)? defaultdict如何获取列表中所有值的总和? - defaultdict how to get sum of all values in a list? 如何从 Python 3.x 中长度不同的多个项目列表中获取值的组合? - How to get a combination of values from multiple list of items with varying length in Python 3.x? Python - 将 (x, y) 坐标分配给列表列表的值 - Python - Assigning (x, y) coordinates to values of list of lists 在python中的成对列表中查找最小x和y值的最佳方法? - Best way to find minimum x and y values in a list of pairs in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM