Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Convert Matrix to overlapping Tuple Pairs

Python – Convert Matrix to overlapping Tuple Pairs

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. 

Python3




# Python3 code to demonstrate working of
# Convert Matrix to overlapping Tuple Pairs
# Using loop
 
# initializing list
test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Matrix to overlapping Tuple Pairs
# Using loop
res = []
for sub in test_list:
  res.append((sub[0], sub[1]))
  res.append((sub[1], sub[2]))
   
# printing result
print("Filtered tuples : " + str(res))


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), 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. 

Python3




# Python3 code to demonstrate working of
# Convert Matrix to overlapping Tuple Pairs
# Using loop + list slicing
 
# initializing list
test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Matrix to overlapping Tuple Pairs
# Using loop + list slicing
res = []
for sub in test_list:
    for idx in range(len(sub) -1):
        res.append(tuple(sub[idx:idx + 2]))
   
# printing result
print("Filtered tuples : " + str(res))


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 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

  • Create a list called “test_list” containing three sublists.
  • Use list comprehension and zip() to create a new list called “res”.
  • The first part of the list comprehension, “for sub in test_list”, iterates through each sublist in “test_list”.
  • The second part of the list comprehension, “for pair in zip(sub, sub[1:])”, iterates through each tuple in the result of “zip(sub, sub[1:])”. “zip(sub, sub[1:])” creates a list of tuples where the first element in each tuple is an element from “sub” and the second element in each tuple is the following element in “sub”.
  • The result of the list comprehension, “tuple(pair)”, creates a new tuple for each pair of elements in “sub”.
  • This tuple contains the first and second elements of the pair.
  • The “res” list is now a list of tuples containing every pair of adjacent elements from each sublist in “test_list”.
  • The “print” statement outputs the filtered tuples in “res” as a string.

Python3




test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]]
 
# using list comprehension and zip()
res = [tuple(pair) for sub in test_list for pair in zip(sub, sub[1:])]
 
# printing result
print("Filtered tuples: " + str(res))


Output

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

  • Import the NumPy library.
  • Convert the input matrix to a NumPy array using the numpy.array() function.
  • Use the numpy.lib.stride_tricks.as_strided() function to create a view of the array with overlapping windows. The window size is (2,2) since we want to create tuples of length 2.
  • Use the numpy.ravel() function to flatten the overlapping windows view into a 1D array.
  • Convert the 1D array into a list of tuples using the zip() function.
  • Print the resulting list of tuples.

Python3




import numpy as np
 
# initializing list
test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Matrix to overlapping Tuple Pairs
# Using NumPy Library
arr = np.array(test_list)
view = np.lib.stride_tricks.as_strided(arr, shape=(arr.shape[0], arr.shape[1]-1, 2), strides=(arr.strides[0], arr.strides[1], arr.strides[1]))
flat_view = np.ravel(view)
res = list(zip(flat_view[::2], flat_view[1::2]))
 
# printing result
print("Filtered tuples : " + str(res))


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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments