Sudoku - checking if there are duplicates in rows&columns

Viewed 262

So my goal is to write a programme that extracts non-zero integers from each row and column and checks if there are any repeated values, and return False if duplicates exist, else return True. It's working fine for rows, but I'm struggling to obtain the non-zero entries in each column. I can only get non-zero entries from one specific column, but I don't know how to iterate through all columns and check for duplicates. I've tried using nested for loops, but it doesn't seem to work because it would just return a list of all non-zero integers from each list in L.

    def sudoku(L):
    #checks the rows
    
    for i in L:
        row=[x for x in i if x != 0]
        for j in row:
            if row.count(j)!=1:
                return False

    #checks the columns
    col=list()
    for x in range(9):
        if L[x][0]!=0:
            col.append(L[x][0])
    print(col)

L = [[5,3,0,0,7,0,0,0,0],
     [6,0,0,1,9,5,0,0,0],
     [0,9,8,0,0,0,0,6,0],
     [8,0,0,0,6,0,0,0,3],
     [4,0,0,8,0,3,0,0,1],
     [7,0,0,0,2,0,0,0,6],
     [0,6,0,0,0,0,2,8,0],
     [0,0,0,4,1,9,0,0,5],
     [0,0,0,0,8,0,0,7,9]]

print(sudoku(L))
2 Answers
    column = [[x[count] for x in L if x[count] != 0] for count in range(9) ]
    for c in column:
        if len(set(c)) != len(c):
            return False
        else:
            return True

set() removes any duplicates

The code can be shortened to

    column = [[x[count] for x in L if x[count] != 0] for count in range(9) ]
    return False not in [True if len(set(c)) == len(c) else False for c in column]

My approach would be to convert the same index for every column to a row, and reuse the code for the rows

L = [[5,3,0,0,7,0,0,0,0],
     [6,0,0,1,9,5,0,0,0],
     [0,9,8,0,0,0,0,6,0],
     [8,0,0,0,6,0,0,0,3],
     [4,0,0,8,0,3,0,0,1],
     [7,0,0,0,2,0,0,0,6],
     [0,6,0,0,0,0,2,8,0],
     [0,0,0,4,1,9,0,0,5],
     [0,0,0,0,8,0,0,7,9]]

columns = []

for i in range(len(L)):
  columns.append([])
  for row in L:
    if row[i] != 0:
      columns[i].append(row[i])

print(columns) #List of columns with no 0’s
Related