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 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 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 to Construct n*m Matrix from List We are given a list we need to construct a n*m matrix from that list. For example, a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] we need to construct a 3*4 matrix so that resultant output becomes [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] .Using List ComprehensionThis method uses list comprehension
3 min read