Home > Back-end >  how to make integer as Key and List as Value in Map in Python?
how to make integer as Key and List as Value in Map in Python?

Time:10-22

I have this input

arr = [1,2,1,3,4,2,4,2]

What I'm trying to achieve is make elements of the given list as keys of a map and its indices as values in the form of a list.

Like this :

mp = {1:[0,2],2:[1,5,7],3:[3],4:[4,6]}

And what will be the time-complexity for this?

CodePudding user response:

from collections import defaultdict

result = defaultdict(list)

for pos, num in enumerate(array):
   result[num].append(pos)
   

Time complexity is O(n), there is only one loop and all things in the loop (looking up thing in dictionary, appending an item) are constant wrt. the number of items.

CodePudding user response:

arr = [1, 2, 1, 3, 4, 2, 4, 2]
mp = {
    num: [i for i, k in enumerate(arr) if i == num]
    for num in set(arr)
}

or normally:

arr = [1, 2, 1, 3, 4, 2, 4, 2]
mp = {}

for num in set(arr):
    mp[num] = []
    for i, k in enumerate(arr):
        if k == num:
            mp[num]  = [i]

Sorry, i do not know much about the time complexities stuff, but naturally two loops, so O(n^2).

CodePudding user response:

try

arr  = [1,2,1,3,4,2,4,2]
d = {}
for n in set(arr):
    d[n] = [i for i, x in enumerate(arr) if x==n]

or

import numpy as np
arr  = [1,2,1,3,4,2,4,2]
arr = np.array(arr)
d = {n:np.where(arr==n)[0].tolist() for n in set(arr)}
  • Related