Codewars: Did I finished my Sudoku?

5kyu的一道题。 没有计算技巧,只是配合 list comprehension、set、map、reduce花样很多。 这次刻意用zip解决。

优秀解答中使用numpy实现的best practice如下:

import numpy as np
def done_or_not(aboard): #board[i][j]
  board = np.array(aboard)

  rows = [board[i,:] for i in range(9)]
  cols = [board[:,j] for j in range(9)]
  sqrs = [board[i:i+3,j:j+3].flatten() for i in [0,3,6] for j in [0,3,6]]

  for view in np.vstack((rows,cols,sqrs)):
      if len(np.unique(view)) != 9:
          return 'Try again!'

  return 'Finished!'

Write a function done_or_not/DoneOrNot passing a board (list[list_lines]) as parameter. If the board is valid return ‘Finished!’, otherwise return ‘Try again!’
这里规则就是采用数独规则


from functools import reduce
SUCCESS = 'Finished!'
FAILED = 'Try again!'
flatten = lambda l: [item for sublist in l for item in sublist]
def done_or_not(board): #board[i][j]
    return SUCCESS if not [1 for row, col, region in
                           zip(board, list(zip(*board)),
                               [ flatten(region) for region in flatten([list(zip(*[zip(*[iter(c)] * 3) for c in t])) for
                                t in zip(*[iter(board)] * 3)])]
                               ) if
                           reduce(lambda x, y: x + y, row) != 45 or reduce(
                               lambda x, y: x + y, col) != 45 or reduce(
                               lambda x, y: x + y,region)!=45] else FAILED

猜你喜欢

转载自blog.csdn.net/qq_35279914/article/details/82193995