SHARE
TWEET

Sudoku Python

a guest Feb 17th, 2020 141 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import random
  2.  
  3. def MakeSudoku():
  4.     Grid = [[0 for x in range(9)] for y in range(9)]
  5.            
  6.     for i in range(9):
  7.         for j in range(9):
  8.             Grid[i][j] = 0
  9.            
  10.     # The range here is the amount
  11.     # of numbers in the grid
  12.     for i in range(5):
  13.         #choose random numbers
  14.         row = random.randrange(9)
  15.         col = random.randrange(9)
  16.         num = random.randrange(1,10)
  17.         while(not CheckValid(Grid,row,col,num) or Grid[row][col] != 0): #if taken or not valid reroll
  18.             row = random.randrange(9)
  19.             col = random.randrange(9)
  20.             num = random.randrange(1,10)
  21.         Grid[row][col]= num;
  22.        
  23.     Printgrid(Grid)
  24.  
  25. def Printgrid(Grid):
  26.     TableTB = "|--------------------------------|"
  27.     TableMD = "|----------+----------+----------|"
  28.     print(TableTB)
  29.     for x in range(9):
  30.         for y in range(9):
  31.             if ((x == 3 or x == 6) and y == 0):
  32.                 print(TableMD)
  33.             if (y == 0 or y == 3 or y== 6):
  34.                 print("|", end=" ")
  35.             print(" " + str(Grid[x][y]), end=" ")
  36.             if (y == 8):
  37.                 print("|")
  38.     print(TableTB)
  39. #     |-----------------------------|
  40. #     | 0  0  0 | 0  0  0 | 0  0  0 |
  41. #     | 0  0  0 | 0  0  0 | 0  0  0 |
  42. #     | 0  0  0 | 0  0  0 | 0  0  0 |
  43. #     |---------+---------+---------|
  44. #     | 0  0  0 | 0  0  0 | 0  0  0 |
  45. #     | 0  0  0 | 0  0  0 | 0  0  0 |
  46. #     | 0  0  0 | 0  0  0 | 0  0  0 |
  47. #     |---------+---------+---------|
  48. #     | 0  0  0 | 0  0  0 | 0  0  0 |
  49. #     | 0  0  0 | 0  0  0 | 0  0  0 |
  50. #     | 0  0  0 | 0  0  0 | 0  0  0 |
  51. #     |-----------------------------|
  52.    
  53. def CheckValid(Grid,row,col,num):
  54.     #check if in row
  55.     valid = True
  56.     #check row and collumn
  57.     for x in range(9):
  58.         if (Grid[x][col] == num):
  59.             valid = False
  60.     for y in range(9):
  61.         if (Grid[row][y] == num):
  62.             valid = False
  63.     rowsection = row // 3
  64.     colsection = col // 3
  65.     for x in range(3):
  66.         for y in range(3):
  67.             #check if section is valid
  68.             if(Grid[rowsection*3 + x][colsection*3 + y] == num):
  69.                 valid = False
  70.     return valid
  71.  
  72. MakeSudoku()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top