Skip to content

Instantly share code, notes, and snippets.

@cyyeh
Created March 26, 2017 03:39
Show Gist options
  • Select an option

  • Save cyyeh/d888ec39b2ff98d3cfefc765e35002aa to your computer and use it in GitHub Desktop.

Select an option

Save cyyeh/d888ec39b2ff98d3cfefc765e35002aa to your computer and use it in GitHub Desktop.
#reference: https://en.wikipedia.org/wiki/Zebra_Puzzle
# keypoint in python here:
#1. generator expression
#2. *args to function calls
#3. itertools module
#4. is (if two variables point to the same object)
#5. rearrage for and if clause to stop program earlier (if not this program may run estimately an hour)
#5. time module
import itertools
import time
def imright (h1, h2):
"House h1 is immediately right of h2 if h1 - h2 == 1"
return h1 - h2 == 1
def nextto(h1, h2):
"Two houses are next to each other if they differ by 1"
return abs(h1 - h2) == 1
def zebra_puzzle():
"Return a tuple (WATER, ZEBRA) indicating their house numbers."
houses = first, _, middle, _, _ = [1, 2, 3, 4, 5]
orderings = list(itertools.permutations(houses)) #1
return next((WATER, ZEBRA)
for (red, green, ivory, yellow, blue) in orderings
if imright(green, ivory) #6
for (Englishman, Spaniard, Ukranian, Japanese, Norwegian) in orderings
if (Englishman is red) #2
if Norwegian is first #10
if nextto(Norwegian, blue) #15
for (coffee, tea, milk, oj, WATER) in orderings
if coffee is green #4
if Ukranian is tea #5
if milk is middle #9
for (OldGold, Kools, Chesterfields, LuckyStrike, Parliaments) in orderings
if Kools is yellow #8
if LuckyStrike is oj #13
if Japanese is Parliaments #14
for (dog, snails, fox, horse, ZEBRA) in orderings
if (Spaniard is dog) #3
if OldGold is snails #7
if nextto(Chesterfields, fox) #11
if nextto(Kools, horse) #12
)
def timedcall(fn, *args):
"Call function with args; return the time in seconds and results."
t0 = time.clock()
result = fn(*args)
t1 = time.clock()
return t1-t0, result
print(timedcall(zebra_puzzle)) # time cost: less than 0.001 second
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment