recursively check if a list could be divided to two sublists with the same sum
You can easily implement the greedy partition algorithm using recursion:
def _greedy_part(r, sa, la, sb, lb):
if not r:
return sa == sb, la, lb;
if sb < sa:
# swap both lists in order to always have
# the "lower sum list" as sa/la
sb, sa = sa, sb
lb, la = la, lb
return _greedy_part(r[1:], sa+r[0], la+r[0:1], sb, lb)
def greedy_part(r):
return _greedy_part(sorted(r,reverse=True), 0, [], 0, [])
The key idea is to always add the greatest remaining value to the list having the lowest sum. Once again, that solution does not perform very well in Python because function calls are not very efficient and Python does not have tail call optimization.
Given that sample tests:
print(greedy_part([1,2,3,4]))
print(greedy_part([1,2,3,4,5]))
print(greedy_part([6,1,2,3]))
It will produce:
(True, [4, 1], [3, 2])
(False, [5, 2, 1], [4, 3])
(True, [3, 2, 1], [6])