직접 시도해보려면 이 프롬프트를 개발자 Console에 복사하세요!

Content
System제공된 자연어 요청을 기반으로 Python 함수를 생성하는 것이 당신의 임무입니다. 요청에는 입력 매개변수와 예상되는 반환 값을 포함하여 함수의 원하는 기능이 설명되어 있습니다. 주어진 명세에 따라 함수를 구현하되, 엣지 케이스를 처리하고, 필요한 유효성 검사를 수행하며, Python 프로그래밍의 모범 사례를 따르도록 하세요. 로직을 설명하고 다른 개발자가 구현을 이해하는 데 도움이 되도록 코드에 적절한 주석을 포함해 주세요.
User스도쿠 퍼즐을 풀 수 있는 함수가 필요합니다. 이 함수는 9x9 스도쿠 그리드를 입력으로 받아야 하며, 빈 칸은 0으로 표시됩니다. 함수는 백트래킹 알고리즘을 사용하여 퍼즐을 풀고 해결된 그리드를 반환해야 합니다. 퍼즐을 풀 수 없는 경우 None을 반환해야 합니다. 또한 함수는 입력 그리드가 유효한 스도쿠 퍼즐인지 확인하기 위해 유효성 검사도 수행해야 합니다.

출력 예시

Python
def solve_sudoku(grid):
   def is_valid(row, col, num):
       # Check if the number is valid in the current row and column
       for i in range(9):
           if grid[row][i] == num or grid[i][col] == num:
               return False

       # Check if the number is valid in the current 3x3 subgrid
       start_row, start_col = (row // 3) * 3, (col // 3) * 3
       for i in range(3):
           for j in range(3):
               if grid[start_row + i][start_col + j] == num:
                   return False

       return True

   def backtrack(row, col):
       # If we have filled all cells, the puzzle is solved
       if row == 9:
           return True

       # Move to the next row if we have reached the end of the current row
       if col == 9:
           return backtrack(row + 1, 0)

       # If the current cell is already filled, move to the next cell
       if grid[row][col] != 0:
           return backtrack(row, col + 1)

       # Try filling the current cell with numbers from 1 to 9
       for num in range(1, 10):
           if is_valid(row, col, num):
               grid[row][col] = num
               if backtrack(row, col + 1):
                   return True
               grid[row][col] = 0

       # If no valid number is found, backtrack
       return False

   # Validate the input grid
   if not all(len(row) == 9 and all(0 <= cell <= 9 for cell in row) for row in grid):
       return None

   # Start the backtracking algorithm
   if backtrack(0, 0):
       return grid
   else:
       return None


API 요청

import anthropic

client = anthropic.Anthropic(  # defaults to os.environ.get("ANTHROPIC_API_KEY")
    api_key="my_api_key",
)
message = client.messages.create(
    model="claude-3-7-sonnet-20250219",
    max_tokens=1000,
    temperature=0,
    system="Your task is to create Python functions based on the provided natural language requests. The requests will describe the desired functionality of the function, including the input parameters and expected return value. Implement the functions according to the given specifications, ensuring that they handle edge cases, perform necessary validations, and follow best practices for Python programming. Please include appropriate comments in the code to explain the logic and assist other developers in understanding the implementation.",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "I want a function that can solve a Sudoku puzzle. The function should take a 9x9 Sudoku grid as input, where empty cells are represented by the value 0. The function should solve the puzzle using a backtracking algorithm and return the solved grid. If the puzzle is unsolvable, it should return None. The function should also validate the input grid to ensure it is a valid Sudoku puzzle.",
                }
            ],
        }
    ],
)
print(message.content)