FindingAlby
FindingAlby

Reputation: 33

Writing a diagonal of a matrix (2D list) function

I want to write a function that accepts one argument, a square 2D matrix, and returns the diagonal of the entered matrix from the interactive window of IDLE.

I have tried several ways but whenever I input a matrix (1 to 16 in a 4 × 4) I get a TypeError saying 4 positional arguments but 5 were given.

I have messed around with it trying to use input() to be able to enter the matrix I want but I still get the same error.

This is what I want to be able to do:

>>> m1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> diagonal(m1)
[1, 6, 11, 16]

How would I go about this? I have also seen a lot of posts using Numpy but I am not entirely sure if it is allowed to use on this assignment.

Upvotes: 0

Views: 66

Answers (2)

SamratV
SamratV

Reputation: 226

Try this:

def diagonal(m1):
    n = len(m1)
    l = []
    for i in range(n):
        l.append(m1[i][i])

    return l

m1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
print(diagonal(m1))

Upvotes: 0

Mark
Mark

Reputation: 92461

enumerate() is very convenient here with a square matrix because it will give you the proper indexes as you loop through your arrays. You can use it in a comprehension to get both the correct index and the correct matrix.

def diagonal(mat):
    return [el[i] for i, el in enumerate(mat)]

m1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

diagonal(m1)
>> [1, 6, 11, 16]

Upvotes: 2

Related Questions