1

I'm trying to accumulate a list of indices of items that occur multiple times, given a list. Not sure how to go about doing that as my code only manages to compare pattern[1] and pattern[2] before terminating.

def test(pattern):
     """(list) -> list of int

     >>> test(['A', 'B', 'A', 'C', 'A'])
     [0, 2, 4]
     >>> test(['A', 'B'])
     []
     """
     indices = []
     new_list = []

     for i in range(len(pattern) - 1): 
          if pattern[i][-1] == pattern[i + 1]:  
              indices.append(i)
              new_list = phoneme_list[max(indices):]

      return new_list
1
  • How long are the lists you're working with? Commented Apr 1, 2015 at 23:56

2 Answers 2

3
>>> lst = ['A', 'B', 'A', 'C', 'A']
>>> [i for i in range(len(lst)) if lst.count(lst[i]) > 1]
[0, 2, 4]

That said, assembling a list of indices probably indicates that your algorithm could be improved.

Sign up to request clarification or add additional context in comments.

Comments

2

I'd do this:

import collections

d = collections.defaultdict(list)

for idx,el in enumerate(lst):
    d[el].append(idx)
    # you can also do this with d as a normal dict, and instead do
    # d.setdefault(el, []).append(idx)

# this builds {'A':[0,1,3], 'B':[2,4], 'C':[5]} from
# ['A','A','B','A','B','C']

result = [idx for idxs in d.values() for idx in idxs if len(idxs) > 1]
# this builds [0,1,3,2,4] from
# {'A':[0,1,3], 'B':[2,4], 'C':[5]}

It also avoids the need to call list.count n times, which should perform massively faster for a larger dataset.

Alternatively you could leverage collections.Counter to get all the values that happen multiple times, then pull all their indices at once.

import collections

c = set([el for el,val in collections.Counter(lst).items() if val>1])
# gives {'A','B'}
result = [idx for idx,el in enumerate(lst) if el in c]
# gives [1,2,3,4]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.