![]() |
VOOZH | about |
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the conversion of matrix elements to their coordinate list. This kind of problem can come in many domains including day-day programming and competitive programming. Lets discuss certain ways in which this task can be performed.
Input : test_list = [['g', 'g', 'g'], ['g', 'g', 'g']] Output : {'g': {(0, 1), (1, 2), (0, 0), (1, 1), (1, 0), (0, 2)}} Input : test_list = [['a', 'b', 'c']] Output : {'a': {(0, 0)}, 'b': {(0, 1)}, 'c': {(0, 2)}}
Method #1 : Using loop + enumerate() The combination of above functionalities can be used to perform this task. In this, we use brute force to extract elements and assign indices to them with the help of enumerate().
The original list is : [['g', 'f', 'g'], ['i', 's', 'g'], ['b', 'e', 's', 't']] The Coordinate Dictionary : {'g': {(1, 2), (0, 0), (0, 2)}, 'f': {(0, 1)}, 't': {(2, 3)}, 'i': {(1, 0)}, 'b': {(2, 0)}, 'e': {(2, 1)}, 's': {(1, 1), (2, 2)}}
Time Complexity: O(n*m) where n is the total number of values in the column and m is the total number of values in the row in the list “test_list”.
Auxiliary Space: O(k) where k is the length of the list “test_list”.
Method #2 : Using setdefault() + loop This method operates in similar way as above, just the difference is that setdefault() reduces the task of memoizing the element value and key presence checks.
The original list is : [['g', 'f', 'g'], ['i', 's', 'g'], ['b', 'e', 's', 't']] The Coordinate Dictionary : {'g': {(1, 2), (0, 0), (0, 2)}, 'f': {(0, 1)}, 't': {(2, 3)}, 'i': {(1, 0)}, 'b': {(2, 0)}, 'e': {(2, 1)}, 's': {(1, 1), (2, 2)}}
Time Complexity: O(n*n) where n is the number of elements in the dictionary. The setdefault() + loop is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the dictionary.