Python – Index Directory of Elements
Last Updated :
08 Mar, 2023
Given a list of elements, the task is to write a python program to compute all the indices of all the elements.
Examples:
Input: test_list = [7, 6, 3, 7, 8, 3, 6, 7, 8]
Output: {8: [4, 8], 3: [2, 5], 6: [1, 6], 7: [0, 3, 7]}
Explanation: 8 occurs at 4th and 8th index, 3 occurs at 2nd and 5th index and so on.
Input: test_list = [7, 6, 3, 7, 8, 3, 6]
Output: {8: [4], 3: [2, 5], 6: [1, 6], 7: [0, 3]}
Explanation: 8 occurs at 4th index, 3 occurs at 2nd and 5th index and so on.
Method #1: Using dictionary comprehension + enumerate() + set()
In this, we get all the indices using enumerate() to append to index list for matching values. Dictionary comprehension is used for iteration of all elements in the list. The set() is used to get all the elements without repetition.
Python3
test_list = [ 7 , 6 , 3 , 7 , 8 , 3 , 6 , 7 , 8 ]
print ( "The original list is : " + str (test_list))
res = {key: [idx for idx, val in enumerate (test_list) if val = = key]
for key in set (test_list)}
print ( "Index Directory : " + str (res))
|
Output:
The original list is : [7, 6, 3, 7, 8, 3, 6, 7, 8]
Index Directory : {8: [4, 8], 3: [2, 5], 6: [1, 6], 7: [0, 3, 7]}
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using dictionary comprehension + groupby() + enumerate() + sorted() + itemgetter()
In this, we sort and group like elements, using groupby() and sorted(). The itemgetter(), is used to get values for sort by values from index and values extracted using enumerate(). Dictionary comprehension is used to get paired index of the grouped result.
Python3
from itertools import groupby
from operator import itemgetter
test_list = [ 7 , 6 , 3 , 7 , 8 , 3 , 6 , 7 , 8 ]
print ( "The original list is : " + str (test_list))
res = {key: [idx for idx, _ in groups] for key, groups in groupby(
sorted ( enumerate (test_list), key = itemgetter( 1 )), key = itemgetter( 1 ))}
print ( "Index Directory : " + str (res))
|
Output:
The original list is : [7, 6, 3, 7, 8, 3, 6, 7, 8]
Index Directory : {3: [2, 5], 6: [1, 6], 7: [0, 3, 7], 8: [4, 8]}
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. The dictionary comprehension + groupby() + enumerate() + sorted() + itemgetter() is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n), new dictionary of size O(n) is created where n is the number of elements in the dictionary
Share your thoughts in the comments
Please Login to comment...