Advertisement
AceFaiuh

Assignment 3 - Question 3

May 12th, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.00 KB | None | 0 0
  1. ===================================================================================================================
  2. Input/Output
  3. ===================================================================================================================
  4. IN:
  5. 059000483
  6. 000000012
  7. 010028000
  8. 098074020
  9. 040080030
  10. 070630540
  11. 000160050
  12. 620000000
  13. 735000860
  14.  
  15. OUT:
  16. 2 5 9 7 1 6 4 8 3
  17. 0 6 0 0 0 0 0 1 2
  18. 0 1 0 0 2 8 0 0 0
  19. 0 9 8 0 7 4 0 2 0
  20. 0 4 0 0 8 0 0 3 0
  21. 0 7 0 6 3 0 5 4 0
  22. 0 8 0 1 6 0 0 5 0
  23. 6 2 0 0 0 0 0 0 0
  24. 7 3 5 0 0 0 8 6 0
  25.  
  26. ===================================================================================================================
  27. Main Function
  28. ===================================================================================================================
  29. # Jethro Muller
  30. # Assignment 9 - Q3: Sudoku Solver
  31. # MLLJET001
  32. # 12.05.2013
  33.  
  34. from TestListQ3 import testSudoku
  35. state = []
  36. def toIntList2D(lst):
  37.     """Function that works with a 2D list as the parameter\nIt returns the list as a list of integers"""
  38.     newLst = []
  39.     for i in range(9):
  40.         newLst.append([int(lst[i][j]) for j in range(9)])
  41.     return newLst
  42.  
  43. def toIntList(lst):
  44.     """Takes a list as the parameter\nIt returns the list as a list of integers"""
  45.     return [int(lst[i]) for i in range(9) if type(lst[i])==str]
  46.  
  47. def inCol(gridN, i, colN):
  48.     """Searches for int i in a column"""
  49.     if i in makeCol(gridN, colN):
  50.         return True
  51.     else:
  52.         return False
  53.  
  54. def makeCol(gridN, colN):
  55.     """Creates the column grid from the grid\nReturns the column grid"""
  56.     vertGrid = []
  57.     for x in range(9):
  58.         placeholder=[]
  59.         for y in range(9):
  60.             placeholder.append(gridN[y][x])
  61.         vertGrid.append(placeholder)
  62.     return vertGrid[colN-1]
  63.  
  64. def inSquare(nGrid,i, rowN, colN):
  65.     """Searches for int i in a grid area"""
  66.     if i in makeSquare(nGrid, rowN, colN):
  67.         return True
  68.     else:
  69.         return False
  70.  
  71. def makeSquare(nGrid, rowN, colN):
  72.     """Creates the specified block from the grid\nReturns the block"""
  73.     newTest =[]    
  74.     newLst = []
  75.    
  76.     for i in range(9):
  77.         newLst.append([str(nGrid[i][j]) for j in range(9)])
  78.     nGrid = newLst
  79.     threeby3 = [[] for i in range(3)]
  80.     for i in range(9):
  81.         newTest.append("".join(nGrid[i]))
  82.         for j, s, e in zip(range(3), [0,3,6], [3,6,9]):
  83.             threeby3[j].append(newTest[i][s:e])
  84.  
  85.     final = [[] for i in range(9)]
  86.     for i,j in zip(range(9),[0,1,2]*3):
  87.         if i<=2:
  88.             final[i] = threeby3[j][0:3]
  89.         elif 3<=i<=5:
  90.             final[i] = threeby3[j][3:6]
  91.         elif 6<=i<=8:
  92.             final[i] = threeby3[j][6:9]
  93.     return final[determineBlock(rowN, colN)-1]
  94.  
  95. def determineBlock(rowN, colN):
  96.     """Determines which block the number is in"""
  97.     a,b,c = [1,2,3],[4,5,6],[7,8,9]
  98.     if rowN in a and colN in a:
  99.         return 1
  100.     elif rowN in b and colN in a:
  101.         return 2
  102.     elif rowN in c and colN in a:
  103.         return 3
  104.     elif rowN in a and colN in b:
  105.         return 4
  106.     elif rowN in b and colN in b:
  107.         return 5
  108.     elif rowN in c and colN in b:
  109.         return 6
  110.     elif rowN in a and colN in c:
  111.         return 7
  112.     elif rowN in b and colN in c:
  113.         return 8
  114.     elif rowN in c and colN in c:
  115.         return 9
  116.  
  117. def populate(grid):
  118.     """Populates the grid by generating values and testing them for each position"""
  119.     nGrid = []
  120.     for i in range(9):
  121.         nGrid.append([int(grid[i][j]) for j in range(9)])
  122.     for i in range(9): # Rows
  123.         rowSet = set(nGrid[i]) #Creates a unique list of numbers from each row
  124.         if 0 in rowSet:
  125.             rowSet.remove(0)
  126.         for j in range(9): #Columns
  127.             toAdd = []
  128.             if nGrid[i][j] ==0:
  129.                 # Creates a unique set of numbers from 1-9 that aren't in the row, column or 3X3 Square
  130.                 for k in [op for op in range(1,10) if op not in rowSet and (inCol(nGrid, op, j+1)==False and inSquare(nGrid, op, i+1, j+1)==False)]:
  131.                     toAdd.append(k)
  132.             if len(toAdd)==1:# If there is only one value in that list, it adds it to the grid
  133.                 nGrid[i][j]=toAdd[0]
  134.             elif len(toAdd)!=0:
  135.                 finalCheck = additionalCheck(nGrid, toAdd, i+1, j+1)
  136.                 if finalCheck!=False:
  137.                     nGrid[i][j] = finalCheck
  138.     print()
  139.     print("Old: ")
  140.     printGrid(toIntList2D(grid))
  141.     print("New: ")
  142.     printGrid(toIntList2D(nGrid))
  143.     return nGrid
  144.  
  145.  
  146. def additionalCheck(grid, toCheck, rowN, colN):
  147.     """The final check before moving on the the next square"""
  148.     print("To Add:",toCheck)
  149.     rowCol = [[1,2,3],[4,5,6],[7,8,9]]
  150.     nRow, nCol = 0,0
  151.     toAdd=[]
  152.     for i in range(len(rowCol)):
  153.         if rowN in rowCol[i]:
  154.             setRC = set(rowCol[i])
  155.             setRC.remove(rowN)
  156.             nRow = list(setRC)
  157.         if colN in rowCol[i]:
  158.             setRC = set(rowCol[i])
  159.             setRC.remove(colN)
  160.             nCol = list(setRC)
  161.     print("Row:",nRow)
  162.     print("Col:",nCol)
  163.     for k in toCheck:
  164.         if (k in grid[nRow[0]-1]) and (k in grid[nRow[1]-1]) and (inCol(grid, k, nCol[0])==True and inCol(grid, k, nCol[1])==True) and inSquare(grid, k, rowN, colN)==False:
  165.             toAdd.append(k)
  166.     if len(toAdd)==1:
  167.         return toAdd[0]
  168.     else:
  169.         return False
  170.  
  171.  
  172. def printGrid(grid):
  173.     """Prints the grid in a user friendly format"""
  174.     for i in range(len(grid)):
  175.         print(" ".join([str(k) for k in grid[i]]))
  176.  
  177.  
  178. def main():
  179.     fi = open("sudoku.txt", "r")
  180.     inFile = fi.read()
  181.     print(inFile)
  182.     grid = [list(i) for i in inFile.split("\n")]
  183.     if testSudoku(grid)==True:
  184.         printGrid(grid)
  185.     else:
  186.         while True:
  187.             newGrid = populate(grid)
  188.             grid=newGrid[:]
  189.             if testSudoku(grid)==True:
  190.                 printGrid(grid)
  191.                 break
  192.        
  193. main()
  194.  
  195.  
  196. ===================================================================================================================
  197. Test Function
  198. ===================================================================================================================
  199.  
  200. def testSudoku(testGrid):#HORIZONTAL CHECK
  201.     for i in testGrid:
  202.         if len(set(i))!=9:
  203.             return False
  204.            
  205.     #CREATE VERTICAL
  206.     vertGrid = []
  207.     for x in range(9):
  208.         placeholder=[]
  209.         for y in range(9):
  210.             placeholder.append(testGrid[y][x])
  211.         vertGrid.append(placeholder)
  212.        
  213.        
  214.     #VERTICAL CHECK
  215.     for i in vertGrid:
  216.         if len(set(i))!=9:
  217.             return False
  218.            
  219.     #CHECK 3X3
  220.     ##Join
  221.     newTest =[]
  222.     threeby3 = list([] for i in range(9))
  223.     for i in range(9):
  224.         newTest.append("".join(testGrid[i]))
  225.         for j, s, e in zip(range(3), [0,3,6], [3,6,9]):
  226.             threeby3[i].append(newTest[i][s:e])
  227.         "".join(threeby3[i])
  228.  
  229.     for i in threeby3:
  230.         if len(set("".join(i)))!=9:
  231.             return False
  232.    
  233.     return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement