Question

I wanted to know why the solution I have written doesn't work:

def transpose(sudoku):
    n = len(sudoku)
    l_tr = [0]*n
    k = 0
    tr_sudoku = [0]*n
    while k < n:
        tr_sudoku[k] = l_tr
        k = k+1  
    i = 0
    for i in range(len(sudoku)):
        j = 0
        for j in range(len(sudoku)):
            tr_sudoku[i][j] = sudoku[j][i]
            print j, i, tr_sudoku, sudoku[i][j]
        print tr_sudoku
return tr_sudoku

correct = [[1,2,3],[2,3,1],[3,1,2]]

print transpose(correct)

It outputs the following incorrect solution:

0 0 [[1, 0, 0], [1, 0, 0], [1, 0, 0]] 1
1 0 [[1, 2, 0], [1, 2, 0], [1, 2, 0]] 2
2 0 [[1, 2, 3], [1, 2, 3], [1, 2, 3]] 3
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
0 1 [[2, 2, 3], [2, 2, 3], [2, 2, 3]] 2
1 1 [[2, 3, 3], [2, 3, 3], [2, 3, 3]] 3
2 1 [[2, 3, 1], [2, 3, 1], [2, 3, 1]] 1
[[2, 3, 1], [2, 3, 1], [2, 3, 1]]
0 2 [[3, 3, 1], [3, 3, 1], [3, 3, 1]] 3
1 2 [[3, 1, 1], [3, 1, 1], [3, 1, 1]] 1
2 2 [[3, 1, 2], [3, 1, 2], [3, 1, 2]] 2
[[3, 1, 2], [3, 1, 2], [3, 1, 2]]
[[3, 1, 2], [3, 1, 2], [3, 1, 2]]

Help would be appreciated! Thanks.

The ideal correct solution to:

correct = [[1,2,4],[2,3,4],[3,4,2]]

would be:

tr_correct = [[1,2,3],[2,3,4],[4,4,2]]
Was it helpful?

Solution

You can easily transpose with zip:

def transpose(sudoku):
    return list(map(list, zip(*sudoku)))

Example output:

>>> correct = [[1,2,3],[2,3,1],[3,1,2]]
>>> transpose(correct)
[[1, 2, 3], [2, 3, 1], [3, 1, 2]]

The easiest "manual" way is to switch rows and columns:

def transpose_manually(sudoku):
    output = sudoku[:] # new grid the same size
    for r in range(len(sudoku)): # each row
        for c in range(len(sudoku[0])): # each column
            output[c][r] = sudoku[r][c] # switch
    return output
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top