Created
January 14, 2014 02:33
-
-
Save zpconn/8412059 to your computer and use it in GitHub Desktop.
This solves a simplified version of the partition problem in polynomial time. Namely, given a list, this finds a pair of sublists of equal length whose sums are the same.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sublists(a, n): | |
if n == 0: | |
return [[]] | |
elif len(a) == 0: | |
return [] | |
else: | |
return sublists(a[1:], n) + [[a[0]] + s for s in sublists(a[1:], n - 1)] | |
def partition(a): | |
if len(a) % 2 != 0: | |
return None | |
halves = sublists(a, len(a) / 2) | |
total = sum(a) | |
for half in halves: | |
if sum(half) == total / 2: | |
other_half = list(a) | |
for x in half: | |
other_half.remove(x) | |
return (half, other_half) | |
return None | |
print partition([3, 1, 1, 2, 2, 1, 4, 9, 3, 2, 9, 1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment