Sort combinations by the sum of their elements in Python

I have a huge list of integers in Python (1,000,000+ elements) , but I will illustrate what I need with an example for simplicity. Suppose I have this list:

A = [1,2,3,4,100]

Now I would like to get all the combinations (size 3) of this list, so I use itertools.

combinations = itertools.combinations(A,3)

But my problem is that this will return the combinations in lexicographical order:

(1,2,3)
(1,2,4)
(1,2,100)
(1,3,4)

etc.

I would like to get combinations sorted by the sum of the elements . This will:

(1,2,3), which sums 6, (1,2,4), which sums 7, (1,3,4), which sums 8,

etc. etc.

How can i achieve this?

+6
source share
2

1,000,000 , 3 , 166 666 166 667 000 000 . , , , .

, . "GENERATING ALL COMBINATIONS" .

,

, :

>>> import itertools
>>> import pprint

>>> A = [1, 2, 3, 4, 100]
>>> combinations = sorted(itertools.combinations(A, 3), key=sum)
>>> pprint.pprint(combinations)
[(1, 2, 3),
 (1, 2, 4),
 (1, 3, 4),
 (2, 3, 4),
 (1, 2, 100),
 (1, 3, 100),
 (1, 4, 100),
 (2, 3, 100),
 (2, 4, 100),
 (3, 4, 100)]

sum() key-function ().

nCr , , , A , , .

+1

- no.of ~ (1000000) ^^ 3 , O (NlogN) . - O (N).

SortedDictionary (sorteddict) -, ​​ memcache, {sum: [tuple1, tuple2]}. ~ O (N)

, . O (N).

O (2N), , O (NLogN). , !

0

Source: https://habr.com/ru/post/1016832/


All Articles