Given a list and a number N, the task here is to write a python program to convert it to matrix where each row has N elements more than previous row elements from list.
Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 3
Output : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Explanation : Each row has 3 elements more than previous row.
Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 4
Output : [[4, 6, 8, 1], [4, 6, 8, 1, 2, 9, 0, 10], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Explanation : Each row has 4 elements more than previous row.
Method 1: Using loop and slicing
In this, we perform the task of getting chunks using slicing, and the conversion of the list into a Matrix is done using a loop.
Program:
Python3
# Initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# Printing original list
print("The original list is : " + str(test_list))
# initializing N
N = 3
# Empty list
res = []
for idx in range(0, len(test_list) // N):
# Getting incremented chunks
res.append(test_list[0: (idx + 1) * N])
# Printing result
print("Constructed Chunk Matrix : " + str(res))
OutputThe original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Time Complexity: O(m*n), where m is the row and n is the column of the matrix
Auxiliary Space: O(k), where k is the size of the matrix
Method 2: Using list comprehension and list slicingĀ
In this, we perform the task of setting values using list comprehension as a shorthand. Rest all the operations are done similarly to the above method.
Program:
Python3
# initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing N
N = 3
# getting incremented chunks
# using list comprehension as shorthand
res = [test_list[0: (idx + 1) * N] for idx in range(0, len(test_list) // N)]
# printing result
print("Constructed Chunk Matrix : " + str(res))
OutputThe original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Time Complexity: O(m*n)
Auxiliary Space: O(k)
Method 3: Using the numpy library's reshape() method.
Here's the step-by-step approach:
- Import the numpy library.
Ā - Initialize the input list and the chunk size.
Ā - Convert the input list to a numpy array.
Ā - Reshape the array to have N columns and as many rows as necessary.
Ā - Convert the chunk matrix back to a Python list.
Ā - Print the result.
Python3
import numpy as np
# initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing N
N = 3
# convert list to numpy array
arr = np.array(test_list)
# reshape array into chunk matrix
chunk_matrix = arr.reshape(-1, N)
# convert chunk matrix back to list
res = chunk_matrix.tolist()
# printing result
print("Constructed Chunk Matrix : " + str(res))
OUTPUT:
The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Constructed Chunk Matrix : [[4, 6, 8], [1, 2, 9], [0, 10, 12], [3, 9, 1]]
Time complexity: O(n), where n is the size of the input list.Ā
Auxiliary space: O(n) for the numpy array, but it is converted back to a Python list, so the overall space complexity is also O(n).
Method 4: Using a recursive function
- Create a list called test_list containing 12 integers.
- Initialize a variable called N to 3, which will be used as the chunk size.
- Define a function called chunk_listĀ
- In the chunk_list function, check if the length of the list is less than or equal to the chunk size. If so, return a list containing the original list.
- If the length of the list is greater than the chunk size, slice the list from the beginning to the chunk size and append it to a new list using the + operator. Then recursively call the chunk_list function with the remaining part of the list until the sublist is less than or equal to the chunk size.
- Call the chunk_list function with test_list and N as arguments and assign the result to a variable called res.
- Print the constructed chunk matrix using the print() function, the string "Constructed Chunk Matrix: ", and the str() function to convert the result to a string.
Python3
# Initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# Printing original list
print("The original list is : " + str(test_list))
# Initializing N
N = 3
def chunk_list(lst, n):
if len(lst) <= n:
return [lst]
else:
return [lst[:n]] + chunk_list(lst[n:], n)
res = chunk_list(test_list, N)
# Printing result
print("Constructed Chunk Matrix : " + str(res))
OutputThe original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Constructed Chunk Matrix : [[4, 6, 8], [1, 2, 9], [0, 10, 12], [3, 9, 1]]
Time complexity: O(N * (L/N)) = O(L), where L is the length of the original list and N is the chunk size.Ā
Auxiliary space: O(L), as it creates a new list for each chunk of the original list.Ā
Method 5: Using the itertools module
Ā can use the zip_longest function from the itertools module to chunk the list into sublists of size N. This method fills the last sublist with a specified value (in this case, None) if its length is less than N.
Python3
from itertools import zip_longest
# Initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# printing original list
print("The original list is: " + str(test_list))
# Initializing N
N = 3
def chunk_list(lst, n):
return [list(filter(None, sublist)) for sublist in zip_longest(*[iter(lst)] * n)]
res = chunk_list(test_list, N)
# Printing result
print("Constructed Chunk Matrix: " + str(res))
OutputThe original list is: [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Constructed Chunk Matrix: [[4, 6, 8], [1, 2, 9], [10, 12], [3, 9, 1]]
Time Complexity: O(N * M), where N is the length of the list and M is the chunk size.
Auxiliary Space: O(N), where N is the length of the list, as the result is stored in a new list.
Similar Reads
Python Program to sort rows of a matrix by custom element count
Given Matrix, the following program shows how to sort rows of a matrix by the count of presence of numbers from a specified list. Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7] Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]] Explanation : 0 < 1 = 1 < 3 i
5 min read
Python3 Program to Modify a matrix by rotating ith row exactly i times in clockwise direction
Given a matrix mat[][] of dimensions M * N, the task is to print the matrix obtained after rotating every ith row of the matrix i times in a clockwise direction.Examples:Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output:1 2 36 4 58 9 7Explanation:The 0th row is rotated 0 times. Therefore, the
2 min read
Python program to Convert a Matrix to Sparse Matrix
Converting a matrix to a sparse matrix involves storing only non-zero elements along with their row and column indices to save memory.Using a DictionaryConverting a matrix to a sparse matrix using a dictionary involves storing only the non-zero elements of the matrix, with their row and column indic
2 min read
Python Program to test whether the length of rows are in increasing order
Given a Matrix, the following program is used to test if length all rows of a matrix are in increasing order or not. If yes, it returns True, otherwise False. Input : test_list = [[3], [1, 7], [10, 2, 4], [8, 6, 5, 1, 4]] Output : True Explanation : 1 < 2 < 3 < 5, increasing lengths of rows
4 min read
Python Program that prints the rows of a given length from a matrix
Given a Matrix, the following articles shows how to extract all the rows with a specified length. Input : test_list = [[3, 4, 5, 6], [1, 4, 6], [2], [2, 3, 4, 5, 6], [7, 3, 1]], K = 3 Output : [[1, 4, 6], [7, 3, 1]] Explanation : Extracted lists have length of 3.Input : test_list = [[3, 4, 5, 6], [1
4 min read
Python - Sort Matrix by Number of elements greater than its previous element
Given a Matrix, sort by occurrences where next element is greater than current. Compute the count of i < i + 1 in each list, sort each row by count of each of this condition in each row. Input : test_list = [[4, 6, 2, 9, 10], [5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2]] Output : [[6, 3, 2], [5, 3
4 min read
Python program to Sort Matrix by Maximum Row element
Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
4 min read
Python program to a Sort Matrix by index-value equality count
Given a Matrix, the task is to write a Python program that can sort its rows or columns on a measure of the number of values equal to its index number. For each row or column, count occurrences of equality of index number with value. After computation of this count for each row or column, sort the m
6 min read
Python Program that filters out non-empty rows of a matrix
Given Matrix, the following article shows how to filter all the Non-Empty rows of a matrix. In simpler terms, the codes provided below return a matrix after removing empty rows from it. Input : test_list = [[4, 5, 6, 7], [], [], [9, 8, 1], []] Output : [[4, 5, 6, 7], [9, 8, 1]] Explanation : All emp
4 min read
Python - Convert String to matrix having K characters per row
Given a String, convert it to Matrix, having K characters in each row. Input : test_str = 'GeeksforGeeks is best', K = 7 Output : [['G', 'e', 'e', 'k', 's', 'f', 'o'], ['r', 'G', 'e', 'e', 'k', 's', ' '], ['i', 's', ' ', 'b', 'e', 's', 't']] Explanation : Each character is assigned to 7 element row
9 min read