import numpy as np from itertools import permutations #a = raw_input() a = "3221, 41, 22, 14, 22, 2313" a = "2124, 23, 13, 22, 41, 3321" a = "1233, 14, 22, 41, 22, 2312" a = "33213, 42, 23 ,15, 22, 21, 22341" a = "23312, 22, 15, 33, 41, 23, 21332" a = [i.strip() for i in a.split(',')] boardSize = len(a[0]) board = [[0] + [int(i) for i in a[0]] + [0]] for i in a[1:-1]: board.append([int(i[0])] + [-1] * boardSize + [int(i[1])]) board.append([0] + [int(i) for i in a[-1]] + [0]) board = np.array(board) stuff = [board[1:-1], board.T[1:-1]] isValid = lambda n: [n[i] > max(n[1:i]) if i > 1 else True for i in range(1, boardSize + 1)].count(True) == n[0] for g in range(2): for i in range(boardSize): if stuff[g][i][0] == 1: stuff[g][i][1] = boardSize elif stuff[g][i][-1] == 1: stuff[g][i][-2] = boardSize #while -1 in board: for q in range(100): for g in range(2): for i in range(boardSize): possible = set(range(1, boardSize + 1)) mightWork = [] for j in stuff[g][i][1:-1]: if j in possible: possible.remove(j) for j in permutations(possible): temp = list(stuff[g][i]) t = 0 for k in range(1, boardSize + 1): if temp[k] == -1: temp[k] = j[t] t += 1 if isValid(temp) and isValid(temp[::-1]): mightWork.append(temp) if len(mightWork) == 1: stuff[g][i] = mightWork[0] print board