![]() |
VOOZH | about |
Sometimes, while working with Python data, we can have a problem in which we need to perform overlap of elements in Matrix, and convert them as tuple pairs. This kind of problem can occur in various application in data domain. Let's discuss certain ways in which this task can be performed.
Input : test_list = [[5, 6, 3], [8, 6, 2], [2, 5, 1]]
Output : [(5, 6), (6, 3), (8, 6), (6, 2), (2, 5), (5, 1)]Input : test_list = [[5, 6, 3]]
Output : [(5, 6), (6, 3)]
Method #1: Using loop This is brute force way in which this task can be performed. In this, we iterate each list and extract consecutive elements and add them as pair in result list.
The original list is : [[5, 6, 7], [8, 6, 5], [2, 5, 7]] Filtered tuples : [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]
Time complexity: O(n), where n is the total number of elements in the matrix.
Auxiliary Space: O(n), where n is the total number of elements in the matrix. This is because the output list 'res' will contain n/2 pairs of elements.
Method #2: Using loop + list slicing The combination of above functionalities can be used to solve this problem. This offers flexibility to extend logic to more custom tuple sizes, more than 2 as well.
The original list is : [[5, 6, 7], [8, 6, 5], [2, 5, 7]] Filtered tuples : [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]
Time complexity: O(n^2), where n is the length of the longest sublist in the matrix.
Auxiliary space: O(n^2), where n is the length of the longest sublist in the matrix.
Method 3 : use list comprehension and the zip() function
Filtered tuples: [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]
Time complexity:O(n^2), where n is the total number of elements in the matrix.
Auxiliary space: O(n^2) because the resulting list contains n^2/2 tuples.
Method #4: Using NumPy Library
Output:
The original list is : [[5, 6, 7], [8, 6, 5], [2, 5, 7]] Filtered tuples : [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]
Time complexity: O(n^2) where n is the length of the input list.
Auxiliary space: O(n) since we create a new array with overlapping windows view, and then flatten it to a 1D array.