Name: Anonymous 2011-09-10 18:34
Python solution to puzzle on this URL: http://www.davar.net/MATH/PROBLEMS/EINSTEIN.HTM
from itertools import permutations
facts = {
'H': 'blue, green, red, white, yellow'.split(', '),
'N': 'Brit, Dane, German, Norwegian, Swede'.split(', '),
'B': 'beer, coffee, milk, tea, water'.split(', '),
'C': 'Blue Master, Dunhill, Pall Mall, Prince, blend'.split(', '),
'P': 'cat, bird, dog, fish, horse'.split(', ')
}
def both(ax, x, ay, y):
for idx, xi in enumerate(x):
if xi == ax and y[idx] == ay: return True
return False
def neighbor(ax, x, ay, y):
return abs(x.index(ax) - y.index(ay)) == 1
def show_answer(h, n, b, c, p):
print '=='
for idx, hi in enumerate(h):
print '%6s %9s %6s %11s %5s' % (hi, n[idx], b[idx], c[idx], p[idx])
for h in permutations(facts['H']):
# 4
if h.index('white') - h.index('green') != 1: continue
for n in permutations(facts['N']):
#1, 9, 14
if not both('Brit', n, 'red', h): continue
if n.index('Norwegian') != 0: continue
if not neighbor('Norwegian', n, 'blue', h): continue
for b in permutations(facts['B']):
# 3, 5, 8
if not both('Dane', n, 'tea', b): continue
if not both('green', h, 'coffee', b): continue
if b.index('milk') != 2: continue
for c in permutations(facts['C']):
# 7, 12, 13, 15
if not both('yellow', h, 'Dunhill', c): continue
if not both('Blue Master', c, 'beer', b): continue
if not both('German', n, 'Prince', c): continue
if not neighbor('blend', c, 'water', b): continue
for p in permutations(facts['P']):
# 2, 6, 10, 11
if not both('Swede', n, 'dog', p): continue
if not both('Pall Mall', c, 'bird', p): continue
if not neighbor('blend', c, 'cat', p): continue
if not neighbor('horse', p, 'Dunhill', c): continue
show_answer(h, n, b, c, p)