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)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?
|
List processing in Python -- Comment() Python is an elegant language, but the lack of some features bothers me. On the other hand, most of the features are easy to implement as Python functions. One of the missing features was a function for "flattening" a nested list structure. Here is some code to provide this functionality: def flatten(L): if not isinstance(L,list): return [L] if L == []: return L return flatten(L[0]) + flatten(L[1:])The output looks like this: [-1, ['a', 'b'], [[1, 2, 3], [1j]], 3] [-1, 'a', 'b', 1, 2, 3, 1j, 3]The tricky part was how to check whether the argument L is not a list. At first I tried just indexing L, and caught the exception in a try: ... except IndexError: structure. But this resulted in an infinitely recursive loop when a list items was a string. The solution above works rather nicely, also for classes which are derived from the list class.
|
Are Mac users the muslims of PC-dominated world? -- Comment() What do Macs and Islam have in common? "The choice to use a Mac or to be Muslim in today's world is not easily understood. In a world where the vast majority of computers are PC, where Islam is perceived as the enemy, why would someone choose to be a Mac user or a Muslim? Bias against both is rampant."
|
-- 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!"
|