1

I am working on a Sudoku Solver in Python, and I need to create functions in it. One of them checks the Sudoku Matrix and returns the number of rows in it that contains a repeating number.

def findRepeatsInColumn(matrix):
    numRepeats = 0
    for row in matrix:
        safeChars=['[', ']', '/']
        usedChars=[]
        for char in str(row):
            if char in usedChars and char not in safeChars:
                numRepeats += 1
                break
            else:
                usedChars.append(char)
    return numRepeats

If I pass a matrix [[1, 1, 1], [2, 2, 2], [3, 3, 3]] to it, it functions fine and gives me the output 3, but for checking all columns for repeated numbers, I need to convert the rows into columns, which means I would need something like: Input: [[1, 1, 1], [2, 2, 2], [3, 3, 3]] Output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]] Any thoughts on how I could do this without NumPy?

4
  • 2
    Suggestion: use numpy, its optimised Commented Apr 4, 2020 at 8:45
  • 1
    Suggestion 2: use [[1, 1, 1], [2, 2, 2], [3, 3, 3]] instead of [[111], [222], [333]] Commented Apr 4, 2020 at 8:54
  • @AngusTay I hardly believe it is easy to vectorize the operations you would need to implement for a sudoku solver. Unless one plans on using Numba. Commented Apr 4, 2020 at 8:55
  • @Angus, transpose in numpy is easy, but iterations like this are slower. Conversion to/from arrays is also slow. Commented Apr 4, 2020 at 14:35

3 Answers 3

1

One simple way is to make use of zip and *:

>>> ip = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

>>> print(list(zip(*ip)))
[(1, 2, 3), (1, 2, 3), (1, 2, 3)]
Sign up to request clarification or add additional context in comments.

Comments

1

Suppose you have a matrix named m

transposed = zip(*m)

Comments

0

if your input isnumpy.array you may use the transpose:

i = np.array([[1,1,1], [2,2,2], [3,3,3]])
print(i.T)

output:

[[1 2 3]
 [1 2 3]
 [1 2 3]]

or you could use:

list(map(list, zip(*i)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.