Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- def print_grid(grid):
- for row in grid:
- print(" ".join(str(num) for num in row))
- def is_valid(grid, row, col, num):
- for i in range(9):
- if grid[row][i] == num or grid[i][col] == num:
- return False
- start_row, start_col = 3 * (row // 3), 3 * (col // 3)
- for i in range(start_row, start_row + 3):
- for j in range(start_col, start_col + 3):
- if grid[i][j] == num:
- return False
- return True
- def fill_grid(grid):
- for row in range(9):
- for col in range(9):
- if grid[row][col] == 0:
- random_nums = list(range(1, 10))
- random.shuffle(random_nums)
- for num in random_nums:
- if is_valid(grid, row, col, num):
- grid[row][col] = num
- if fill_grid(grid):
- return True
- grid[row][col] = 0
- return False
- return True
- def generate_sudoku():
- grid = [[0] * 9 for _ in range(9)]
- fill_grid(grid)
- return grid
- def check_for_sevens(grid, num_samples=30):
- flat_grid = [num for row in grid for num in row]
- selected_tiles = random.sample(flat_grid, num_samples)
- has_seven = 7 in selected_tiles
- return has_seven
- # Generate a completed Sudoku grid
- sudoku_grid = generate_sudoku()
- # Print the Sudoku grid
- print("Generated Sudoku Grid:")
- print_grid(sudoku_grid)
- # Run 1,000,000 trials to check for 7s
- num_trials = 1000000
- count_no_sevens = 0
- for _ in range(num_trials):
- if not check_for_sevens(sudoku_grid):
- count_no_sevens += 1
- # Calculate percentage of no-7s
- percentage_no_sevens = (count_no_sevens / num_trials) * 100
- # Output results
- print(f"Total occurrences of no 7s: {count_no_sevens}")
- print(f"Percentage of trials with no 7s: {percentage_no_sevens:.4f}%")
- input()
Advertisement
Add Comment
Please, Sign In to add comment