# 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)