Skip to content

Instantly share code, notes, and snippets.

@dnene
Created October 31, 2011 00:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnene/1326624 to your computer and use it in GitHub Desktop.
Save dnene/1326624 to your computer and use it in GitHub Desktop.
Broken Weight problem
# Response to challenge at http://beust.com/weblog/2011/10/30/a-new-coding-challenge/
# Further (braintwistingly) compact version of the same logic : https://gist.github.com/1326654
import itertools
n = 40
weights = tuple((w1,w2,w3,n-(w1+w2+w3)) for w1 in range(1,n) for w2 in range(w1,n - w1) for w3 in range(w2, n-w1-w2) if n-(w1+w2+w3) -w3 >= 0)
for weight in weights :
allvals = list(val for val in range(1,n + 1))
for clength in range(1,5) :
for combo in itertools.combinations(weight,clength) :
other = list(weight)
for c in combo :
other.remove(c)
for olength in range(len(other) + 1) :
for o in itertools.combinations(other,olength) :
diff = abs(sum(combo) - sum(o))
if diff in allvals : allvals.remove(diff)
if len(allvals) == 0 : print weight
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment