Reputation: 76
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.
Upvotes: 0
Views: 69
Reputation: 11606
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]
Upvotes: 1