Loading...
    • Руководство разработчика
    • Справочник API
    • MCP
    • Ресурсы
    • Примечания к выпуску
    Search...
    ⌘K
    Ресурсы
    ОбзорГлоссарийСистемные промпты
    Библиотека промптовCosmic KeystrokesCorporate clairvoyantWebsite wizardExcel formula expertGoogle apps scripterPython bug busterTime travel consultantStorytelling sidekickCite your sourcesSQL sorcererDream interpreterPun-ditCulinary creatorPortmanteau poetHal the humorous helperLaTeX legendMood colorizerGit gudSimile savantEthical dilemma navigatorMeeting scribeIdiom illuminatorCode consultantFunction fabricatorNeologism creatorCSV converterEmoji encoderProse polisherPerspectives pondererTrivia generatorMindfulness mentorSecond-grade simplifierVR fitness innovatorPII purifierMemo maestroCareer coachGrading guruTongue twisterInterview question crafterGrammar genieRiddle me thisCode clarifierAlien anthropologistData organizerBrand builderEfficiency estimatorReview classifierDirection decoderMotivational museEmail extractorMaster moderatorLesson plannerSocratic sageAlliteration alchemistFuturistic fashion advisorPolyglot superpowersProduct naming proPhilosophical musingsSpreadsheet sorcererSci-fi scenario simulatorAdaptive editorBabel's broadcastsTweet tone detectorAirport code analyst
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    Библиотека промптов

    Генератор функций

    Создавайте функции Python на основе подробных спецификаций.

    Скопируйте этот промпт в наш Консоль разработчика, чтобы попробовать его самостоятельно!

    Содержание
    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

    Was this page helpful?

    • Пример вывода
    • Запрос API