Truble to create a matrix for sudoku in python

2024/11/17 2:58:11

I have to make a sudoku template, so I need to get random numbers into the matrix, but they can not be repeated in the rows or columns, but I can not do it. For this I can not use numpy. In this case I did in the code below but it does not work:

import random
matrix = []
for i in range(9):line = []for j in range(9):number = random.randint(1, 9)if number != i and number != j:line.append(number)matrix.append(line)for i in range(9):print(matrix[i])
Answer

A sudoku board has very little chance of being valid with random numbers. You will need a topological sort (dynamic programming) to satisfy the row, column and block constraints.

For example:

known = [ [0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0]]import random
groups  = [ p//27*3+p%9//3   for p in range(81) ]
colNums = [ set(range(1,10)) for _ in range(9)  ]
rowNums = [ set(range(1,10)) for _ in range(9)  ]
grpNums = [ set(range(1,10)) for _ in range(9)  ]
sudoku  = [ [0]*9 for _ in range(9) ]
for pos in range(81):row,col,group = pos//9,pos%9,groups[pos]fixed = known[row][col]if fixed:sudoku[row][col] = fixedcolNums[col].discard(fixed)rowNums[row].discard(fixed)grpNums[group].discard(fixed)pos     = 0
tried   = [ set() for _ in range(81)]
while pos in range(81):row,col,group    = pos//9,pos%9,groups[pos]number = sudoku[row][col]fixed  = known[row][col]if number != 0 and not fixed:sudoku[row][col] = 0colNums[col].add(number)rowNums[row].add(number)grpNums[group].add(number)available  = {fixed} if fixed else colNums[col] & rowNums[row] & grpNums[group]available -= tried[pos]if available:number = fixed or random.choice(list(available))if not fixed:sudoku[row][col] = numbercolNums[col].discard(number)rowNums[row].discard(number)grpNums[group].discard(number)tried[pos].add(number)pos += 1else:tried[pos] = set()pos -= 1if pos < 81:print("FAILED!")            
else :for r,line in  enumerate(sudoku):print(*[line[i:][:3] for i in range(0,9,3)],"\n"*(r%3==2))

This algorithm attempts to fill the each position using the remaining numbers that are not already used on the same row, column or group (block). The colNums,rowNums and grpNums variables keep track of the remaining available numbers in each column, row and group. When a position cannot be filled, the algorithm backtracks to the previous position and tries another number that has not yet been tried for that position.

The known matrix can be initialized with fixed values that will be forced at their respective position in the resulting sudoku matrix. It can be used to solve sudoku problems or to validate that a problem is doable.

https://en.xdnf.cn/q/120257.html

Related Q&A

Password validation in python with regex without duplicate chars

The parameter is a string. Check whether it forms a secure password.A password is safe ifthere is at least a lowercase letter in it, and there is at least one capital letter in it, and there is at leas…

Processing non-english text

I have a python file that reads a file given by the user, processes it, and ask questions in flash card format. The program works fine with an english txt file but I encounter errors when trying to pro…

Downloading all zip files from url

I need to download all the zip files from the url: https://www.ercot.com

sql to query set

I have 2 tables:puzz_meeting_candidats :- id, canceled, candidat_id, meeting_id puzz_meeting :- id, ClientI have a query follow: SELECT U1.`candidat_id` AS Col1 FROM `puzz_meeting_candidats` U1 INN…

Google App Engine, best practice to schedule code execution [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

delete rows by date and add file name column for multiple csv

I have multiple "," delimited csv files with recorded water pipe pressure sensor data, already sorted by date older-newer. For all original files, the first column always contains dates forma…

X = Y = Lists vs Numbers [duplicate]

This question already has answers here:Immutable vs Mutable types(20 answers)How do I clone a list so that it doesnt change unexpectedly after assignment?(24 answers)Closed 4 years ago.In python : I h…

Python data text file grades program

Looking for help with my program. There is a text file with 5 first and last names and a number grade corresponding to each person. The task is to create a user name and change the number grade to a le…

how to fill NA with mean only for 2 or less consequective values of NA

I am new to python. please help me how I should proceed. The following dataframe contains large blocks of NaNs. # Fill the NAs with mean only for 2 or less consecutive values of NAs. # Refer to the d…

Build a new dictionary from the keys of one dictionary and the values of another dictionary

I have two dictionaries:dict_1 = ({a:1, b:2,c:3}) dict_2 = ({x:4,y:5,z:6})I want to take the keys from dict_1 and values from dict_2 and make a new dict_3dict_3 = ({a:4,b:5,c:6})