Given 2 Matrix, with 2 elements in each row, group them on basis on first element.
Input : test_list1 = [[2, 0], [8, 4], [9, 3]], test_list2 = [[8, 1], [9, 7], [2, 10]]
Output : {2: [0, 10], 8: [4, 1], 9: [3, 7]}
Explanation : All values after mapping cross Matrix, 2 mapped to 0 and 10.
Input : test_list1 = [[8, 4], [9, 3]], test_list2 = [[8, 1], [9, 7]]
Output : {8: [4, 1], 9: [3, 7]}
Explanation : All values after mapping cross Matrix.
This is one of the ways in which this task can be performed. In this, we iterate add both the lists and then form groups from similar elements and convert to dictionary with value list.
OutputThe original list 1 : [[5, 8], [2, 0], [8, 4], [9, 3]]
The original list 2 : [[8, 1], [9, 7], [2, 10], [5, 6]]
The Grouped Matrix : {5: [8, 6], 2: [0, 10], 8: [4, 1], 9: [3, 7]}
This is yet another way in which this task can be performed. In this, we iterate for all the elements of both matrix by converting each to dictionary and group its values. Its important to have traces of each element's mapping in both the Matrix.
OutputThe original list 1 : [[5, 8], [2, 0], [8, 4], [9, 3]]
The original list 2 : [[8, 1], [9, 7], [2, 10], [5, 6]]
The Grouped Matrix : {5: [8, 6], 2: [0, 10], 8: [4, 1], 9: [3, 7]}
Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements
OutputThe original list 1 : [[5, 8], [2, 0], [8, 4], [9, 3]]
The original list 2 : [[8, 1], [9, 7], [2, 10], [5, 6], [5, 9]]
The Grouped Matrix : {8: [4, 1], 9: [3, 7], 2: [0, 10], 5: [8, 6, 9]}
Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements