-1
n,m=map(int,input().split())
arr=[i%m for i in (map(int,(input().split())))]

suppose n=5 and m =3 and input array =[3, 2 ,1 ,4, 5] so arr=[0, 2, 1, 1, 2] in this case but now i want to store elements of equal value in a list efficiently i.e [1,1] and [2,2].What's the best way to group them together efficiently?Also i want their indices at the end so

output : [[1,1],[2,2]] from index (2,3) and index(1,4)

what i am looking for is the indices of the original array elements before taking mod that have the same value after performing mod operation.

9
  • No, it can't be done in less than O(N). You need to iterate over all elements once to group.
    – Martijn Pieters
    Dec 30, 2017 at 11:05
  • So what would the expected output be?
    – Martijn Pieters
    Dec 30, 2017 at 11:06
  • So 0 isn't included because it's unique? What would an input list of [1, 2, 1, 1, 2] be? Dec 30, 2017 at 11:11
  • 2
    @Demonking28 then maybe you should ask that question then? :) Because there's plenty of ways to group the data - but your example lends itself towards answers that won't immediately be that useful for what you actually are after (and what would the output be based on wanting their indices?) Dec 30, 2017 at 11:19
  • 2
    @Demonking28 okay - you need to make that very clear in the question itself - as it's not obvious and people won't read all the comments... (not to mention - are you able 1-based indices - as Python's are 0-based - so your example indices don't immediately make a lot of sense) Dec 30, 2017 at 11:25

1 Answer 1

3

set saves only unique values

arr=[0, 2, 1, 1, 2]
arr = [(s, arr.count(s)) for s in  set(arr)]
#  [(0, 1), (1, 2), (2, 2)]

update (thanks to @JonClements)

s = {}
for i, v in enumerate(arr):
  s.setdefault(v % 3, []).append(i)
print(s)
# {0: [0], 1: [2, 3], 2: [1, 4]}
4
  • That could have been done using counter too Counter(arr) but that won't preserve the index. I think i didn't made it clear in the question but now i have edited the question. My apologies. Dec 30, 2017 at 11:28
  • Instead of the try/except - use s.setdefault(v, []).append(i) Dec 30, 2017 at 11:39
  • And then, you might as well go the whole hog and not bother creating arr since it's probably not of use by itself and have: for i, v in enumerate(array): s.setdefault(v % 3, []).append(v) Dec 30, 2017 at 11:41
  • I did not know the 1st and missed the 2nd from the question text. Thanks you
    – splash58
    Dec 30, 2017 at 11:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.