I’ve been learning programming and Python for about a month now using Udacity. For one of the questions we are supposed to write a function that checks if a sudoku list passed in is valid.
In the for loop below, I wanted to iterate through row and col at the same time with both the original and transposed list using zip() but mistakenly left in row in the second half of my or statement. I ran it and to my surprise, it still continued to return a correct answer.
def check_sudoku(array):
is_sudoku = True
reference = range(1, len(array) + 1)
transposed = zip(array)
for row, col in zip(array, transposed):
if sorted(row) != reference or sorted(row) != reference:
is_sudoku = False
break
return is_sudoku
My guess is it’s because I defined is_sudoku = True by default, and I’m comparing rows with a reference list so it catches invalid values even if my transpose didn’t work. When I replaced the second row with col though, it broke.
My question is, is my guess right? If not, why does this code work and how could I better write this?
Thanks! (Pasted on codepad as well if you want to see what lists I passed in – http://codepad.org/IXDlZuUu)
If the correct value was False, then your function works because at some point
sorted(row) != reference. As for rewriting it, I’d think something like this would be more clear:Additionally, it’s pretty hard for me to see why you do
transposed = zip(array)and thenzip(array, transposed). As far as I can tell that just takes a list like[1, 2, 3]and turns it into[(1, (1,)), (2, (2,)), (3, (3,))].If you are looking to iterate through the rows and columns, here’s one method that works.