Home > Blockchain >  Python function to find matching elements of the list and return the indices of those elements
Python function to find matching elements of the list and return the indices of those elements

Time:02-24

I am trying to write a function called “doubleIndices” that takes a list as input. As output, the function should return the indices of matching elements (that will be two integers, if they exist) and if not then it returns None, None otherwise.

For example, doubleIndices([1,2,3]) would return None, None

doubleIndices([1,2,3,1]) would return 0,3

doubleIndices([1,1,1,1]) can return any two indices that match (e.g. 0,1 or 1,2 or 1,3 or 0,3, you only have to return one pair, not all of them)

I want to write this function in Python and I know it could be written like: if some_condition: return index 1, index 2 else: return None, None

While I also know it could be written with two different loops. Can you guys help me out?

CodePudding user response:

Create set from the passed list and iterate through it, checking each time weather the current element is exist inside the original list, and you can store the matching indices in a list of tuples.

CodePudding user response:

An answer could be:

def dbl(l):
  for i in range(len(l)):
    if (l[i] in l[(i 1):len(l)]):
      return (i,l[(i 1):len(l)].index(l[i]) 1)
  return 0
  • Related