Skip to content

Instantly share code, notes, and snippets.

@wasabili
Created January 1, 2011 11:44
Show Gist options
  • Save wasabili/761701 to your computer and use it in GitHub Desktop.
Save wasabili/761701 to your computer and use it in GitHub Desktop.
SEND+MORE=MONEY
amb_variable_name = []
amb_possible = []
def amb(v, l):
"""
set global variable for amb evaluator
"""
amb_variable_name.append(v)
amb_possible.append(l)
def comb(lol):
"""
make all combination from a list of lists
"""
if not lol:
yield []
else:
for x in lol[0]:
for y in comb(lol[1:]):
yield [x] + y
def ambeval():
"""
amb evaluator
"""
for tp in comb(amb_possible):
print "processing:", tp
# set variables
for name, var in zip(amb_variable_name, tp):
exec(name + "= " + str(var))
# check requirements
met = True
for f in require:
if not eval(f):
met = False
break
# all requiements met
if met:
yield tp
amb("a", (4,6,7))
amb("b", (5,8,11))
require = ["isprime(a+b)"]
from math import *
def isprime(n):
for i in range(2,floor(sqrt(n))+1):
if n % i == 0:
return False
return True
for re in ambeval():
print re
import sys
sys.exit(0)
### main
digit = set(range(10)) # 0..9
amb('s', digit)
amb('e', digit)
amb('n', digit)
amb('d', digit)
amb('m', digit)
amb('o', digit)
amb('r', digit)
amb('y', digit)
def decimal(*args): # [3,4,6,2] -> 3462
return reduce(lambda a,b: a*10+b, args)
require = ['decimal(s,e,n,d) + decimal(m,o,r,e) == decimal(m,o,n,e,y)']
def all_different(): # s != e and s != n and ... and r != y
from itertools import combinations
c = combinations('sendmory', 2)
s = ''
for p in c:
s += "{0} != {1} and ".format(p[0],p[1])
s += "True"
require.append(s)
all_different()
for result in ambeval():
print result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment