0

I need to find 2 same greatest number of elements in list and show the value

Example:

[1, 2, 3, 6] => (1+2+3, 6) => 6

[1, 2, 2, 4, 5, 6] => (1+2+2+5, 4+6) => 10

[1, 2] => can't find same amounts => 0

I have no idea how to do this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Entro
  • 76
  • 1
  • 5
  • 4
    Please show your attempts. SO isn't a code-writing service. Also do read [how to ask](https://stackoverflow.com/help/how-to-ask) – Pynchia Jan 18 '20 at 15:05
  • look at this : https://stackoverflow.com/questions/11344827/summing-elements-in-a-list – BpY Jan 18 '20 at 15:06
  • 1
    Here's what you're looking for - [Geeksforgeeks - Partition Problem](https://www.geeksforgeeks.org/print-equal-sum-sets-array-partition-problem-set-2) – Ajay Dabas Jan 18 '20 at 15:24
  • @AjayDabas wow, thanks! – Entro Jan 18 '20 at 16:07

1 Answers1

1

This gives you the partitions of elements which sum up to half the sum of all the elements in the input list, ordered by descending difference of length between the two partitions:

import itertools as it


def partitions(lst):
    s = sum(lst)
    half_s = s // 2
    if half_s*2 != s:
        raise ValueError(f"Impossible to split the sum {s} evenly")

    combs_all = (it.combinations(lst, k) for k in range(len(lst)))
    combs_poss = (c for ck in combs_all for c in ck if sum(c) == half_s)

    combs_res = []
    for a,b in it.combinations(combs_poss, 2):
        if not set(a).intersection(b):
            combs_res.append([a, b])

    return sorted(combs_res, key=lambda tc: abs(len(tc[0])-len(tc[1])))


l1 = [1,2,3,6]
l2 = [1,2,2,4,5,6]
l3 = [1,2,1,4,4,5,3,2]

print(partitions(l1))
print(partitions(l2))
print(partitions(l3))

which produces:

[[(6,), (1, 2, 3)]]
[[(1, 4, 5), (2, 2, 6)], [(4, 6), (1, 2, 2, 5)]]
[[(4, 4, 3), (1, 2, 1, 5, 2)]]

You are free to pick the element you prefer, e.g. the first one

partitions(l2)[0]
Pynchia
  • 10,996
  • 5
  • 34
  • 43