user2403149
user2403149

Reputation:

How can I refactor this line of code:

I'm writing a program to check if sudoku is solved. Here is a part which I can't think of a way to refactor:

for i in range(0, 9):
    for j in range(0, 9):
        if i < 3:
            if j < 3:
                one.append(sudoku[i][j])
            if j >= 3 and j < 6:
                two.append(sudoku[i][j])
            if j >= 6:
                three.append(sudoku[i][j])
        if i >= 3 and i < 6:
            if j < 3:
                four.append(sudoku[i][j])
            if j >= 3 and j < 6:
                five.append(sudoku[i][j])
            if j >= 6:
                six.append(sudoku[i][j])
        if i >= 6:
            if j < 3:
                seven.append(sudoku[i][j])
            if i >= 6 and j >= 3 and j < 6:
                eight.append(sudoku[i][j])
            if j >= 6:
                nine.append(sudoku[i][j])    

Thanks!

Upvotes: 0

Views: 58

Answers (2)

Parker
Parker

Reputation: 8851

Try using a 2D array to hold your objects and map them as follows:

mapping = [[one, two, three], [four, five, six], [seven, eight, nine]]

for i in range(0, 9):
    for j in range(0, 9):
        square = mapping[i/3][j/3]
        square.append(sudoku[i][j])

If you are using Python 3, you would replace square = mapping[i/3][j/3] with square = mapping[int(i/3)][int(j/3)] or square = mapping[i//3][j//3] as Padraic pointed out

The reason for this is that Python2 will round down and return an int for division, where as Python3 will return a float. Casting to an int will round down.

Upvotes: 1

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

Put all your blocks one, two, etc... in an array. Then pick the right block in the array, depending on i and j. Basically, you want this index:

index = (i / 3) * 3 + j / 3

Where you are doing integer division.

Upvotes: 0

Related Questions