Balance two lists till their sums are equal & with min swaps within the two lists in Python

Viewed 953
a = [70, 30, 33, 23, 4, 4, 34, 95]
b = [50, 10, 10, 7]

I've tried this, but i know this is not accurate enough

if sum(a) > sum(b):
   a.sort()
   b.sort()
   temp = [int(i) for i in a]
   i=0
   while(sum(b) <= sum(temp)  and (i <= len(a) - 1)):
      b.append(a[i])
      temp.remove(a[i])
      i = i+1

    a = [int(i) for i in temp]
if sum(b) > sum(a):
    a.sort()
    b.sort()
    temp = [int(i) for i in b]
    i=0
    while(sum(a) <= sum(temp)  and (i <= len(b) - 1)):
        a.append(b[i])
        temp.remove(b[i])
        i = i+1        

    b = [int(i) for i in temp]

Result was:

sums = 186, 184

lists = [7, 10, 70, 95, 4], [4, 10, 23, 30, 33, 34, 50]

Required Answer :

sums = 185, 185

lists = [7, 10, 23, 50, 95], [4, 4, 10, 30, 33, 34, 70]

3 Answers
Related