File size: 5,139 Bytes
1b8214f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# Filename: Generate_sudokuCSV.py (v1.2 - API FIX)
# Description: This version corrects the bug where the '.solution' attribute
# was incorrectly accessed. It now properly uses the '.solve()'
# method as required by the 'py-sudoku' library API.
import os
import sys
import subprocess
# --- Environment Setup and Dependency Installation ---
def setup_dependencies():
"""Checks for and installs required packages ('py-sudoku' and 'pandas')."""
print("--- Checking Dependencies ---")
try:
import sudoku
import pandas
print("Dependencies 'py-sudoku' and 'pandas' are already satisfied.")
return
except ImportError:
print("A required package is missing. Attempting installation...")
packages_to_install = ['py-sudoku', 'pandas']
try:
command = [sys.executable, "-m", "pip", "install"] + packages_to_install
print(f"Running command: {' '.join(command)}")
subprocess.check_call(command)
print("--- Dependencies installed successfully. ---")
except subprocess.CalledProcessError as e:
print("\nFATAL: Failed to install required packages automatically.")
print("Please run this command in a new cell: !pip install py-sudoku pandas")
sys.exit(f"Installation failed with error: {e}")
# Run the dependency check immediately
setup_dependencies()
# Now we can safely import the libraries
from sudoku import Sudoku
import pandas as pd
# --- CORE GENERATION FUNCTION (for portability) ---
def Generate_sudokucsv(num_puzzles: int = 10000, difficulty: float = 0.7, output_path: str = './sudoku.csv'):
"""
Generates a specified number of Sudoku puzzles and their solutions,
saving them to a CSV file.
Args:
num_puzzles (int): The number of puzzles to generate.
difficulty (float): The difficulty of the puzzles (0.0 to 1.0).
output_path (str): The file path for the output CSV.
Returns:
bool: True if the file was created or already exists, False on failure.
"""
print("\n" + "="*50)
print("Sudoku CSV Generator Initialized")
print(f"Puzzles to generate: {num_puzzles}")
print(f"Difficulty setting: {difficulty}")
print(f"Output file: {output_path}")
print("="*50)
if os.path.exists(output_path):
print(f"INFO: File '{output_path}' already exists. Skipping generation.")
return True
board_to_string = lambda board: "".join(str(cell) if cell is not None else '0' for row in board for cell in row)
data = []
print("Generating puzzles... this may take a few moments.")
try:
for i in range(num_puzzles):
puzzle_obj = Sudoku(3, 3).difficulty(difficulty)
quiz_board = puzzle_obj.board
# --- API FIX IS HERE ---
# 1. Call the .solve() method on the original puzzle object.
solved_puzzle_obj = puzzle_obj.solve()
# 2. Get the .board attribute from the NEW solved object.
solution_board = solved_puzzle_obj.board
if quiz_board is None or solution_board is None:
# This might happen if the generator creates an invalid/unsolvable puzzle
print(f"\nWarning: Skipping puzzle {i+1} due to generation/solving error.")
continue
data.append({
'quizzes': board_to_string(quiz_board),
'solutions': board_to_string(solution_board)
})
# Progress indicator
progress = (i + 1) / num_puzzles
bar_length = 40
filled_len = int(bar_length * progress)
bar = '█' * filled_len + '-' * (bar_length - filled_len)
sys.stdout.write(f'\rProgress: |{bar}| {progress*100:5.1f}%')
sys.stdout.flush()
print("\n\nGeneration complete. Creating DataFrame and saving to CSV...")
if not data:
print("ERROR: No data was generated. Cannot create CSV file.")
return False
df = pd.DataFrame(data)
df.to_csv(output_path, index=False)
if os.path.exists(output_path):
print(f"SUCCESS: '{output_path}' created with {len(df)} puzzles.")
return True
else:
print(f"FAILURE: An error occurred and '{output_path}' was not created.")
return False
except Exception as e:
print(f"\nAn unexpected error occurred during generation: {e}")
import traceback
traceback.print_exc()
return False
# --- MAIN EXECUTION BLOCK ---
if __name__ == '__main__':
try:
from google.colab import files
output_file_path = 'sudoku.csv'
print(f"Running in Google Colab. Output will be saved to '{output_file_path}'.")
except ImportError:
output_file_path = './sudoku.csv'
print(f"Running in local environment. Output will be saved to '{output_file_path}'.")
# Execute the generation process
Generate_sudokucsv(num_puzzles=20000, difficulty=0.7, output_path=output_file_path) |