【问题标题】:Finding Unique Triplets Combinations to the provided Sum list在提供的 Sum 列表中查找唯一的 Triplets 组合
【发布时间】:2020-04-19 11:49:25
【问题描述】:

我有一系列这样的数字

lst = [30.25, 30.0, 19.0, 31.25, 28.25, 28.25, 29.25, 28.5, 26.5, 26.5, 25.25, 24.25, 23.75, 23.5, 20.5, 20.0, 21.75, 21.25, 21.0, 19.75, 20.0]

现在我想计算总和等于给定数字(目标)的所有此类可能组合。

我从第四眼中发现了这个非常强大的代码部分:

def subsets_with_sum(lst, target, with_replacement=False):
    x = 0 if with_replacement else 1
    def _a(idx, l, r, t):
        if t == sum(l): r.append(l)
        elif t < sum(l): return
        for u in range(idx, len(lst)):
            _a(u + x, l + [lst[u]], r, t)
        return r
return _a(0, [], [], target)

我的目标是验证是否有 3 或 4 个(在运行代码之前选择)子列表与 lst 中的唯一项目的组合,并打印找到的三元组或四元组。

如果不是:建议 1 或 2 个值来实现目标。

PS:正如您所见,lst 由十进制小时的值组成 对于我的具体情况,我的目标是 168(一周内的小时数)

【问题讨论】:

    标签: python list function sum combinations


    【解决方案1】:

    使用itertools.combinations

    from collections import defaultdict
    import itertools
    
    lst = [30.25, 30.0, 19.0, 31.25, 28.25, 28.25, 29.25, 28.5, 26.5, 26.5, 25.25, 24.25, 23.75, 23.5, 20.5, 20.0, 21.75, 21.25, 21.0, 19.75, 20.0]
    
    def subsets_with_sum(lst, target, ncomb, nsuggest):
        # try to get match for ncomb
        matches = [comb for comb in itertools.combinations(lst, ncomb) if sum(comb) == target]
        if matches:
            return list(set(matches))
    
        # suggest values
        # build up dict of target - sum(comb)
        suggestions = defaultdict(int)
        for comb in itertools.combinations(lst, ncomb - 1):
            suggestion = target - sum(comb)
            if suggestion > 0:
                suggestions[suggestion] += 1
        sorted_suggestions = sorted([(value, key) for (key,value) in suggestions.items()], reverse=True)
        return [item[1] for item in sorted_suggestions[0:ncomb]]
    

    输出

    >>>subsets_with_sum(lst, 115, 4, 2)                                                                                 
    [(30.25, 30.0, 28.25, 26.5),
     (30.0, 31.25, 28.5, 25.25),
     (30.25, 31.25, 28.25, 25.25),
     (30.25, 30.0, 31.25, 23.5),
     (30.25, 31.25, 29.25, 24.25),
     (30.0, 28.25, 28.25, 28.5)]
    
    >>>subsets_with_sum(lst, target=215, ncomb=4, nsuggest=2)                                                                                 
    [140.25, 138.5]
    

    【讨论】:

    • 首先感谢您的快速答复!它真的对我有帮助!我可能没有很好地解释,但在你的情况下,有 6 个 ncomb,我想将其限制为 3 或 4,在我的情况下,项目的数量限制为 4,我不想限制它。最后,建议必须在 32 到 18 小时之间,并且每个子列表中的值必须是其他子列表中使用的唯一蚂蚁
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 2021-11-08
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多