Skip to content

Instantly share code, notes, and snippets.

@czheo
Last active April 14, 2018 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save czheo/42082a6d42223054ba1be41edf1f7ab1 to your computer and use it in GitHub Desktop.
Save czheo/42082a6d42223054ba1be41edf1f7ab1 to your computer and use it in GitHub Desktop.
l = [509, 838, 924, 650, 604, 793, 564, 651,
697, 649, 747, 787, 701, 605, 644]
def by_dp():
dp = [0] * 5001
i = 0
while i < len(l):
w = 5000
while w >= l[i]:
n_w = dp[w - l[i]] + l[i]
if n_w <= w:
dp[w] = max(n_w, dp[w])
w -= 1
i += 1
return(dp[-1])
def powerset(l):
'get powerset'
if len(l) == 1:
return [l, []]
sub = powerset(l[1:])
return [[l[0]] + r for r in sub] + sub
def by_powerset():
'find max sum in powerset'
return max(
filter(
lambda x: sum(x) <= 5000,
powerset(l)
),
key=sum
)
print(by_powerset())
print(by_dp())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment