Home > Software engineering >  Shift and shuffle the rows of a matrix
Shift and shuffle the rows of a matrix

Time:07-26

I have a matrix as follows.

mat = [[23,45,56,67],
       [12,67,09,78],
       [20,59,48,15],
       [00,06,51,90]]

I want to write a function where depending on the argument passed to the function, the rows of the matrix must be shifted and shuffled. For eg: if the argument passed to the function is 2, then the 2nd row of the matrix mat must be made as 0th row while the rest of the rows 1-3 must be shuffled as shown below.

value = 2

mat = [[20,59,48,15],
       [00,06,51,90],
       [23,45,56,67],
       [12,67,09,78]]

The rows 1-3 in the above matrix should be randomly shuffled. One example of how the matrix should look like is shown above.

Is there a way to write a function for this?

Thanks!

CodePudding user response:

mat = [[23,45,56,67],
       [12,67,9,78],
       [20,59,48,15],
       [0,6,51,90]]

def shift(mat, row_index):
    return mat[row_index:]   mat[:row_index]

for row in shift(mat, 2): print(row)   

Output

[20, 59, 48, 15]
[0, 6, 51, 90]
[23, 45, 56, 67]
[12, 67, 9, 78]

EDIT :

My bad, I didn't read the shuffle randomly part. Here's the right function, put the 2th row in first place and shuffle the rest of the matrix.

def shift_and_shuffle(mat, row_index):
    rest_mat = mat[row_index 1:]   mat[:row_index]
    return [mat[row_index]]   random.sample(rest_mat, len(rest_mat))

CodePudding user response:

the following function should work :

from random import shuffle
def shift_and_shuffle(mat: list, shift: int) -> list:
    mat_copy = mat[:]
    res = [mat_copy[shift]]
    mat.remove(mat_copy[shift])
    shuffle(mat_copy)
    return res   mat_copy

CodePudding user response:

Use list concatenation

import random
def function(mat, n):
    m = mat[n]
    for i in range(len(mat)):
        if i == n:
            continue  # Skip the line you don't want to shuffle
        random.shuffle(mat[i])
        m  = mat[i]
    return m
  • Related