# Solution to the Zen Archery problem by leonardo maffi, V1.1, Feb 24 2007 # Problem URL: www.merriampark.com/comb.htm # Given the following 24 numbers taken 5 at a time, which unique combinations # adds up to 200? d = [97,101,139,41,37,31,29,89,23,19,8,13,131,19, 73,97,19,139,79,67,61,17,113,127] import csp # http://www.fantascienza.net/leonardo/so/csp.zip """ # Wrong version: p = csp.Problem("RecursiveBacktracking") p.addvars("abcde", d) p.alldifferent() p.addrule("a+b+c+d+e == 200") sols = p.solutions() print map(list, set(frozenset(s[v] for v in "abcde") for s in sols)) """ p = csp.Problem() p.addvars("abcde", enumerate(d)) p.alldifferent() # This is the faster rule I have found p.addrule(lambda a,b,c,d,e: a[1]+b[1]+c[1]+d[1]+e[1]==200) sols, t = csp.timing(p.solutions) sols2 = (tuple(sorted(s[v][1] for v in "abcde")) for s in sols) sols3 = sorted(set(sols2)) print t, "secs", len(sols3), "solutions:", sols3