fork download
  1. # Ref http://p...content-available-to-author-only...e.com/questions/2194/color-the-table
  2. from itertools import permutations, ifilter
  3. #-----------------------------------------------------------
  4. def inColumn(x,y): # Return true if x,y are in same column.
  5. dxy = abs(x-y)
  6. return dxy == 6 or dxy == 3
  7. #-----------------------------------------------------------
  8. def nextTo(x,y): # Return true if x,y are Manhattan-adjacent.
  9. dxy = abs(x-y)
  10. return dxy == 1 or dxy == 3
  11. #-----------------------------------------------------------
  12. # Test if permutation p satisfies all conditions.
  13. def isGood(p):
  14. B, G, K, L, O, P, R, W, Y = p
  15. # Tests 1 and 2.
  16. # Note, digit 3 is in cell 1 and digit 5 is in cell 0
  17. # 1. nextTo(Y,O); not nextTo(R, B)
  18. # 2. color(number(3)) in {W,G,L,R}; color(number(5)) not in {W,P};
  19. if nextTo(R, B) or not nextTo(Y,O) or \
  20. 1 not in (W,G,L,R) or 0 in (W,P):
  21. return False
  22. # Tests 3 and 4.
  23. # 3. inColumn(P,O); not inColumn(Y,B); not inColumn(G,L)
  24. # 4. abs(number(W)-number(K)) == 1; not nextTo(W,K)
  25. if not inColumn(P,O) or inColumn(Y,B) or inColumn(G,L) or \
  26. abs(number[W]-number[K]) != 1 or nextTo(W,K):
  27. return False
  28. # Tests 5 and 6.
  29. # 5. abs(number(R)-number(Y)) < 3; abs(number(W)-number(L)) < 4
  30. # 6. abs(number(R)-number(L)) > 2
  31. if abs(number[R]-number[Y]) > 2 or abs(number[W]-number[L]) > 3 \
  32. or abs(number[R]-number[L]) < 3:
  33. return False
  34. # Tests 7, 8, 9.
  35. # 7. nextTo(G,K); odd(number(G))
  36. # 8. not inColumn(R,Y)
  37. # 9. number(L) > number(G)
  38. if not nextTo(G,K) or not number[G]&1 or \
  39. inColumn(R,Y) or \
  40. number[L] <= number[G]:
  41. return False
  42. return True
  43. #---------------------------Main program--------------------
  44. cellNums = [0, 1, 2, 3, 4, 5, 6, 7, 8]
  45. digCells = [7, 8, 1, 6, 0, 3, 4, 2, 5]
  46. number = [5, 3, 8, 6, 7, 9, 4, 1, 2]
  47. colors = ['black', 'green', 'pink', 'blue', 'orange', 'purple', 'red', 'white', 'yellow']
  48.  
  49. for p in ifilter(isGood, permutations(cellNums)):
  50. for cn in digCells:
  51. for j, c in enumerate(p):
  52. if c==cn: print colors[j],
  53. print
  54.  
Success #stdin #stdout 0.39s 7896KB
stdin
Standard input is empty
stdout
yellow red green orange black purple white pink blue
yellow red green orange black purple pink white blue
green black red purple yellow orange pink white blue