Oct-17-2023, 05:58 PM
Good evening,
i am doing some exercises from the course i am attending and one of them is requiring me to realize with base Python a valid sudoku 4x4 grid.
With base python i mean that we cannot use:
1) external lybraries (only the random lybraries)
2) personal functions (we didn't covered them yet)
I have written an example of code that i put here below.
My code have some problems:
1) It doesnt check if we have same number in same column
2) It doesnt check if we have same number in same 2x2 grid
3) I tried to fill the void spaces with "" using multiple while. I think the same output can be done using one for and one while?
Thanks for the help
i am doing some exercises from the course i am attending and one of them is requiring me to realize with base Python a valid sudoku 4x4 grid.
With base python i mean that we cannot use:
1) external lybraries (only the random lybraries)
2) personal functions (we didn't covered them yet)
I have written an example of code that i put here below.
My code have some problems:
1) It doesnt check if we have same number in same column
2) It doesnt check if we have same number in same 2x2 grid
3) I tried to fill the void spaces with "" using multiple while. I think the same output can be done using one for and one while?
Thanks for the help
import random sudoku = list() number = list() difficulty = 7 # max number of elements in sudoku # Generating a 4x4 table with random number between 1 and 4 for row in range (4): column = list() for i in range(4): column.append(random.randint(1,4)) # Removing duplicates and counting number of elements per row sudoku.append(list(set(column))) number.append(len(sudoku[row])) # Counting the total number of elements elements = sum(number) # Removing last element from random row until we reach the desired number of elements while elements > difficulty: sudoku[random.randint(1,3)].pop() elements = elements - 1 print(sudoku) # Adding spaces where we have no elements row_0 = len(sudoku[0]) row_1 = len(sudoku[1]) row_2 = len(sudoku[2]) row_3 = len(sudoku[3]) while row_0 < 4: sudoku[0].append("") row_0 = len(sudoku[0]) while row_1 < 4: sudoku[1].append("") row_1 = len(sudoku[1]) while row_2 < 4: sudoku[2].append("") row_2 = len(sudoku[2]) while row_3 < 4: sudoku[3].append("") row_3 = len(sudoku[3]) print(sudoku)