Open In App

Python Program to Reverse Every Kth row in a Matrix

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Matrix, the task is to write a python program to reverse every Kth row. Where K is some span value.

Input : test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 4 
Output : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [6, 3], [3, 7, 4], [2, 9]]
Explanation : Every 4th row is reversed.
Input : test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 2 
Output : [[5, 3, 2], [3, 6, 8], [3, 5, 2], [6, 3], [3, 7, 4], [9, 2]]
Explanation : Every 2nd row is reversed. 

Method 1 : Using reversed() and loop

In this, we iterate for each row, and if the Kth row is found, reversal of it is performed using reverse().

Example:

Python3




# Python3 code to demonstrate working of
# Reverse Kth rows in Matrix
# Using reversed() + loop
 
# initializing list
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2],
             [3, 6], [3, 7, 4], [2, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
res = []
for idx, ele in enumerate(test_list):
 
    # checking for K multiple
    if (idx + 1) % K == 0:
 
        # reversing using reversed
        res.append(list(reversed(ele)))
    else:
        res.append(ele)
 
# printing result
print("After reversing every Kth row: " + str(res))


Output

The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [9, 2]]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 2: Using Slicing and list comprehension

In this, the task of reversing is performed using string slice, and list comprehension is used as shorthand to perform task of iteration.

Example:

Python3




# Python3 code to demonstrate working of
# Reverse Kth rows in Matrix
# Using Slicing + list comprehension
 
# initializing list
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2],
             [3, 6], [3, 7, 4], [2, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
# using enumerate() to get index and elements.
# list comprehension to perform of iteration
res = [ele[::-1] if (idx + 1) % K == 0 else ele for idx,
       ele in enumerate(test_list)]
 
# printing result
print("After reversing every Kth row: " + str(res))


Time Complexity: O(n)

Space Complexity: O(n)

Method 3 : Using index() and reverse() methods

Python3




# Python3 code to demonstrate working of
# Reverse Kth rows in Matrix
 
# initializing list
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2],
            [3, 6], [3, 7, 4], [2, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
res = []
for i in test_list:
    if(test_list.index(i)==K-1):
        i.reverse()
        res.append(i)
    else:
        res.append(i)
# printing result
print("After reversing every Kth row: " + str(res))


Output

The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [2, 9]]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using range() function

Python3




# Python3 code to demonstrate working of
# Reverse Kth rows in Matrix
 
# initializing list
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2],
             [3, 6], [3, 7, 4], [2, 9]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
for i in range(K-1, len(test_list), K):
    test_list[i] = test_list[i][::-1]
# printing result
print("After reversing every Kth row: " + str(test_list))


Output

The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [9, 2]]

Time complexity: O(n), where n is the length of the test_list. The range() function takes O(n) time
Auxiliary Space: O(n), extra space of size n is required

Method #5: Using itertools and islice() method

  1. Define the input matrix test_list and the value of K, which indicates the frequency of row reversal.
  2. Initialize a loop that starts from the Kth row and iterates through the matrix with a step of K.
    Within the loop, use the reversed() function to reverse the order of elements in the current Kth row. This creates a reversed iterator object that points to the original list, so no additional memory is used to store the reversed row.
  3. Use the islice() function from the itertools module to limit the length of the reversed iterator to the original length of the row. This is necessary because reversed() returns a reversed iterator that extends beyond the original length of the list, so we need to truncate the iterator to prevent it from including extra elements.
  4. Convert the truncated reversed iterator object to a list object using the list() function, and replace the original Kth row with the reversed list.
  5. After completing the loop, the input matrix will have every Kth row reversed. Print the modified matrix to verify the result.

Python3




from itertools import islice
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
# printing original list
print("The original list is : " + str(test_list))
K = 3
for i in range(K-1, len(test_list), K):
    test_list[i] = list(islice(reversed(test_list[i]), len(test_list[i])))
 
# printing result
print("After reversing every Kth row: " + str(test_list))
#This code is contributed by Rayudu.


Output

The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [9, 2]]

Time complexity : O(N*K), where N is the number of rows in the matrix and K is the frequency of row reversal. This is because the code iterates over each Kth row and reverses the order of its elements using reversed() and islice(), which takes O(K) time.
Auxiliary Space: O(N*K), as the matrix is modified in place and no additional data structures are created. The islice() function returns an iterator that lazily evaluates the reversed list elements, so it doesn’t create a new list object in memory.



Previous Article
Next Article

Similar Reads

Python - Reverse sort Matrix Row by Kth Column
Sometimes, while working with data, we can have a problem in which we need to perform sorting of each row of records by some of decisive factor like score. This kind of problem is common in competitive programming and web development. Lets discuss certain ways in which this task can be performed. Method #1 : Using sorted() + lambda + reverse The co
4 min read
Python Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Python | Reverse Sort Row Matrix integration
Often during problem solving we come across to many problems where we need to reverse sort the list. But sometimes we would also want to reverse sort another list so that the elements of are automatically shifted and remain at same index as the first list even after first list get reverse sorted. Let’s discuss certain ways in which this can be done
7 min read
Python | Operate on every Kth element of list
We generally wish to employ a particular function to all the elements in a list. But sometimes, according to the requirement, we would wish to employ a particular functionality to certain elements of the list, basically to every Kth element in list. Let's discuss certain ways in which this can be performed. Method #1: Using list comprehension + enu
5 min read
Python | Every Kth element in list
Sometimes, while working with Python lists, we can have a problem in which we require to extract every Kth element of list and slice out a new list from that. This type of problems are quite common as a variation of list slicing. Let's discuss a way in which this can be done. Method : Using list slicing This task can be performed using list slicing
3 min read
Python | Every Kth element removal in List
We generally wish to employ a particular function to all the elements in a list. But sometimes, according to requirement we would wish to remove certain elements of the list, basically to every Kth element in list. Let’s discuss certain ways in which this can be performed. Method #1 : Using list comprehension + enumerate() The functionality of gett
5 min read
Python - Every Kth index Maximum in List
We generally wish to employ a particular function to all the elements in a list. But sometimes, according to requirement we would wish to employ a particular functionality to certain elements of the list, basically to every Kth element in list. Let’s discuss certain ways in which maximum of these elements can be performed. Method #1 : Using list co
4 min read
Python - Extract Kth element of every Nth tuple in List
Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6,
8 min read
Python - Cross Join every Kth segment
Given two lists, extract alternate elements at every Kth position. Input : test_list1 = [4, 3, 8, 2, 6, 7], test_list2 = [5, 6, 7, 4, 3, 1], K = 3 Output : [4, 3, 8, 5, 6, 7, 2, 6, 7, 4, 3, 1] Explanation : 4, 3, 8 after that 5, 6 from other list are extracted, and so on.Input : test_list1 = [4, 3, 8, 2], test_list2 = [5, 6, 7, 4], K = 2 Output : [
6 min read
Python - Every Kth Strings Uppercase
Given a String list, change every Kth string to uppercase. Input : test_list = ["gfg", "is", "best", "for", "geeks"], K = 3 Output : ['GFG', 'is', 'best', 'FOR', 'geeks'] Explanation : All Kth strings are uppercased. Input : test_list = ["gfg", "is", "best", "for", "geeks"], K = 4 Output : ['GFG', 'is', 'best', 'for', 'GEEKS'] Explanation : All Kth
4 min read
three90RightbarBannerImg