从总和递减的值集中找到大小r的组合 [英] Find combinations of size r from a set with decreasing sum value

查看:56
本文介绍了从总和递减的值集中找到大小r的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组数字,例如 [100,90,80,70,60,50] ,并希望找到大小为 r = 3 的所有组合,但顺序为总和递减.例如,按降序排列数字不起作用.

I have a set of numbers eg. [100,90,80,70,60,50] and want to find all combinations of size r=3 but in order of decreasing sum. Arranging the numbers in decreasing order does not work eg.

(100, 90, 80) 270
(100, 90, 70) 260
(100, 90, 60) 250
(100, 90, 50) **240**
(100, 80, 70) **250**
(100, 80, 60) 240

我该如何找到总和值减小的组合集.

How can i go about finding such a combination set with decreasing sum value.

推荐答案

代码在这里

import itertools

array = [100,90,80,70,60,50]
size = 3
answer = [] # to store all combination
order = [] # to store order according to sum
number = 0 # index of combination

for comb in itertools.combinations(array,size):
    answer.append(comb)
    order.append([sum(comb),number]) # Storing sum and index
    number += 1

order.sort(reverse=True)  # sorting in decreasing order

for key in order:
    print key[0],answer[key[1]] # key[0] is sum of combination

以上代码的输出为

270 (100, 90, 80)
260 (100, 90, 70)
250 (100, 80, 70)
250 (100, 90, 60)
240 (90, 80, 70)
240 (100, 80, 60)
240 (100, 90, 50)
230 (90, 80, 60)
230 (100, 70, 60)
230 (100, 80, 50)
220 (90, 70, 60)
220 (90, 80, 50)
220 (100, 70, 50)
210 (80, 70, 60)
210 (90, 70, 50)
210 (100, 60, 50)
200 (80, 70, 50)
200 (90, 60, 50)
190 (80, 60, 50)
180 (70, 60, 50)

这篇关于从总和递减的值集中找到大小r的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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