Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. sstr = '''
  2. 71 4
  3. 6 8
  4. 3 4 16
  5. 6 1
  6. 3 8
  7. 1 7 2
  8. 8 9
  9. 53 4 2
  10. 4 1 9 '''
  11.  
  12.  
  13. sudoku1_s8 = '''
  14. 9 65 4 1
  15. 5 83 9
  16. 4 26 3
  17. 36 751
  18. 54 2 3 68
  19. 796 45
  20. 6 57 8
  21. 3 86 7
  22. 7 2 49 6'''
  23.  
  24.  
  25. sudoku_sz_1 = '''
  26. 3596 412
  27. 67
  28. 82 6
  29. 216 5483
  30. 874361952
  31. 248761
  32. 621
  33. 8132675
  34. 621 783 '''
  35.  
  36.  
  37. class State(object):
  38. def __init__(self, sstr):
  39. cnt = 0
  40. state = [dict([(str(i+1),1) for i in range(9)]) for x in range(81)]
  41. for line in sstr.split('\n'):
  42. if len(line)>1:
  43. for c in line:
  44. if c in '123456789':
  45. state[cnt] = c
  46. cnt+=1
  47. self.state = state
  48.  
  49.  
  50. def row(self, n):
  51. row = self.state[n*9:(n+1)*9]
  52. return row
  53. def col(self, n):
  54. col = [self.state[9*x+n] for x in range(9)]
  55. return col
  56. def sq(self, n):
  57. row = n/3
  58. col = n%3
  59. sq = [self.state[9*(3*row+j) + 3*col+i] for j in range(3) for i in range(3)]
  60. return sq
  61. def eliminate(self, elems):
  62. fixeds = [e for e in elems if type(e) != dict]
  63. for f in fixeds:
  64. for e in elems:
  65. if type(e) == dict and f in e:
  66. del e[f]
  67. def clean(self):
  68. for e, x in enumerate(self.state):
  69. if type(x) == dict and len(x) == 1:
  70. self.state[e] = x.keys()[0]
  71.  
  72. def elimround(self):
  73. for fun in [self.row, self.col, self.sq]:
  74. for i in range(9):
  75. elems = fun(i)
  76. self.eliminate(elems)
  77. self.clean()
  78.  
  79.  
  80. def __str__(self):
  81. sstr = ''
  82. cnt = 0
  83. for e in self.state:
  84. if type(e) == dict:
  85. sstr+=' '
  86. else:
  87. sstr+=e
  88. cnt+=1
  89. if cnt%9==0:
  90. sstr+='\n'
  91.  
  92. return sstr
  93.  
  94.  
  95.  
  96. s = State(sudoku_sz_1)
  97. print s
  98. for i in range(10):
  99. s.elimround()
  100.  
  101. print s
  102.  
  103. print s.state
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement