1

I have little problem here. As I am not good in math I can't figure this out tho.

I need to create function that takes n as a parameter which is matrix size and creates matrix of this type

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

All I achieved was this

def arrange_matrix2(n):
    matrix = []
    row = []
    num = 1
    for i in range(n):
        for j in range(n):
            row.append(num)
            num += 1
        matrix.append(row)
        row = []

    final_matrix = map(list, zip(*matrix))
    print(*final_matrix)

It creates matrix that looks like this

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

Also. Is there a way to create matrix that is arranged by column without using zip() function?

Thank you for your time.

4
  • actually you are moving from top->bottom->top-->bottom this is the pattern Commented Mar 26, 2020 at 18:15
  • I know theory. I have no idea how to implement it Commented Mar 26, 2020 at 18:19
  • This is a snake pattern. geeksforgeeks.org/… Commented Mar 26, 2020 at 18:21
  • If you will search by snake pattern you will get lot of resources :) Commented Mar 26, 2020 at 18:21

1 Answer 1

2

You don't need to do anything fancy here. First, preallocate your output:

final_matrix = [[0] * n for _ in range(n)]

Now you can do whatever you want with the indices. For example, here is a very simple approach:

num = 1
for j in range(n):
    for i in range(n):
        if j % 2:
            final_matrix[-(i + 1)][j] = -num
        else:
            final_matrix[i][j] = num
        num += 1

The modulo operator returns the remainder, and can therefore be used to check for divisibility. j % 2 will be 1 if j is odd, 0 if even. So odd columns get reversed and negated. The row index -(i + 1) is a Python shorthand for n - (i + 1). As the actual i goes 0->n-1, the index of odd columns goes n-1->0.

Sign up to request clarification or add additional context in comments.

2 Comments

that is what I needed. Thank you a lot. And for explanation too :)
Start small. If you understand the simple things, you understand everything. If you only know complicated things, you're just fooling yourself.

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.