Lets say that in Python I need to generate a 2d matrix that is n*n. The list should be filled first left to right, then right to left, and so on, how?

Question:

Lets say that in Python I need to generate a 2d matrix that is n * n. My function get’s a parameter "n" and it generates a n*n list, such as

for n = 3

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

That isn’t the problem. My function needs to make a 2d list which is first filled left to right, then right to left, and so on… How do i do this?

Example;

for n = 3

it should generate:

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

and for n = 4:

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

Asked By: Fuke B

||

Answers:

the simpler way is just to reverse the list every other step

m = []
for line in range(n):
   if n%2 == 0:
      m.append([*range(line*n,line*n+n)])
   else:
      m.append([*range(line*n+n,line*n,-1)])
Answered By: Axeltherabbit

here a straightforward solution but probably not the best:

n = 5
matrix = []
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]

def fill_matrix(arr):
    index = 0
    for i in range(n):
        holder = []
        for _ in range(n):
            holder.append(primes[index])
            index += 1
        if i%2 != 0:
            arr.append(list(reversed(holder)))
        else:
            arr.append(holder)
        

fill_matrix(matrix)
print(matrix)

this will output for n=5: [[2, 3, 5, 7, 11], [29, 23, 19, 17, 13], [31, 37, 41, 43, 47], [71, 67, 61, 59, 53], [73, 79, 83, 89, 97]]

Answered By: TheQuestioner

Here I have used some cool python methods like list slicing and ternary operator to make it short and sweet.

n = 5
primes = 
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
matrix = [primes[i:i+n] if i%2==0 else primes[i:i+n][::-1] for i in 
range(0,len(primes),n)]
print(matrix)
Answered By: Selvaganapathy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.