Book Reviews


[Day Permalink] Monday, May 24, 2004

[Item Permalink] Solving the Einstein's Riddle in Python -- Comment()
Using the skills so far learned I managed to implement a Python code for solving the so-called Einstein's Riddle. I solved the problem in two ways, first the straightforward way by using lists and list comprehensions, etc. Then I refactored to code using the Python object model, by deriving new datatypes from the Python list object. This object-oriented version (updated the link on May 29, 2007) is about 50% slower, but easier to understand. Here follows a short extract from the object-oriented version:
def alltrue(l, op=operator.and_):
    return reduce(op, l)

def anytrue(l, op=operator.or_): return reduce(op, l)

class Pattern(list): def __eq__(self, other): return alltrue([u==v for (u,v) in zip(self,other) if u!='_']) def match(self, street): return anytrue([self==h for h in street]) def __call__(self, street): return [h for h in street if self.match(h)] def nr(self, street): for i in xrange(len(street)): if self==street[i]: return i

class House(list): pass

class Street(list): def __init__(self,*l): try: self[:] = [House()+h for h in l[0]] except IndexError: self[:] = [House() for i in xrange(5)] def new(self,items): st = Street(self[:]) [h.append(d) for (h,d) in zip(st,items)] return st def __str__(self): t = unzip(self) s = '' for u in t: s = s + ''.join([("%-10s" % str(v)) for v in u]) + 'n' return s

My input data was in Finnish, so I'm afraid the following result may be difficult to read:
1         2         3         4         5         
kelt      sini      pun       vihr      valk      
norja     tanska    suomi     saksa     ruotsi    
vesi      tee       maito     kahvi     olut      
blues     ooppera   rock      iskelma   hevi      
kissa     hevonen   lintu     kalat     koira     
(Also, I don't like smoking, so I changed that part of the data to different types of music.)

But what is the final solution? Well, the German ('saksa') owns the fish ('kalat') in house 4.

Here is a follow-up question. What if we interpret the rule

4. The Green house is on the left of the White house.
so that there may be houses between the Green and White house. How many different solutions do you get?


[Item Permalink]  -- Comment()
Camilo commented The Mathematics of Marriage: "I read James Murray's Mathematical Biology, and it is awesome; he is one of the authors of the book, and a superb researcher and expert in NLD. I do intend to get my hands on this book!"