Найти - Пользователи
Полная версия: Судоку
Начало » Python для новичков » Судоку
1
Kurtz
# Define a procedure, check_sudoku,
# that takes as input a square list
# of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square and returns the boolean False
# otherwise.
# A valid sudoku square satisfies these
# two properties:
#   1. Each column of the square contains
#       each of the whole numbers from 1 to n exactly once.
#   2. Each row of the square contains each
#       of the whole numbers from 1 to n exactly once.
# You may assume the the input is square and contains at
# least one row and column.
correct = [[1,2,3],
           [2,3,1],
           [3,1,2]]
incorrect = [[1,2,3,4],
             [2,3,1,3],
             [3,1,2,3],
             [4,4,4,4]]
               
def check_sudoku(p):
    n = len(p)
    digit = 1
    while digit <= n:
        i = 0
        while i < n:
            row_count = 0
            col_count = 0
            j = 0
            while j < n:
                if p[i][j] == digit:
                    row_count = row_count + 1
                if p[j][i] == digit:
                    col_count = col_count + 1
                j = j + 1
            if row_count != 1 or col_count != 1:
                return False
            i = i + 1
        digit = digit + 1
    return True
    
#print check_sudoku(incorrect)
#>>> False
print check_sudoku(correct)
#>>> True

Здравствуйте.
Есть задача по Судоку, суть которой в создании функции, которая в качестве переменных берет несколько списков и проверяет их на то, чтобы в каждой строке и каждом столбце квадрата, каждая цифра от 1 до n встречалось только один раз. Есть решение этой задачи.
Как вы понимаете это решение?
FishHook
Берем список, кастуем его к множеству, сравниваем длину множества с длиной списка.
Kurtz
Что означает
p[i][j]
и
p[j][i]
?
Kir@
Как форматированный набор из 33 строк кода, который в итоге выдает 4 строки:
>>> 
False
True
>>>
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB