Search code examples
pythonlist-comprehension

Using comprehension list create a matrix with cross pattern


Without using numpy I need to create a matrix that looks like this:

1 0 0 0 1
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1

So far I have only been able to get this pattern:

1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

using this comprehension list:

l = [[1 if i == j else 0 for j in range(5)] for i in range(5)]

Now I need to figure out how to change the counter diagonal to same pattern using comp list.


Solution

  • Try this -

    n=7
    [[1 if i==j or i+j==n-1 else 0 for j in range(n)] for i in range(n)]
    
    [[1, 0, 0, 0, 0, 0, 1],
     [0, 1, 0, 0, 0, 1, 0],
     [0, 0, 1, 0, 1, 0, 0],
     [0, 0, 0, 1, 0, 0, 0],
     [0, 0, 1, 0, 1, 0, 0],
     [0, 1, 0, 0, 0, 1, 0],
     [1, 0, 0, 0, 0, 0, 1]]