Python Forum
Sudoku making with base Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sudoku making with base Python
#1
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

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)
Larz60+ write Oct-17-2023, 05:49 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
I modified your code this time. Please use BBCode tags on future posts.
Reply


Messages In This Thread
Sudoku making with base Python - by wep - Oct-17-2023, 05:58 PM
RE: Sudoku making with base Python - by deanhystad - Oct-18-2023, 04:37 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  how to get the sudoku solver to work? Tool1211 8 3,251 Feb-03-2022, 04:49 PM
Last Post: BashBedlam
  Code by Voice using Python ( Need HELP in making ADVANCE ) pawandeore 0 1,463 Feb-24-2021, 06:59 PM
Last Post: pawandeore

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020