Home > front end >  Searching through a list with given elements
Searching through a list with given elements

Time:12-09

I am trying to create a function that accepts two lists of integers, where the second list is a subset of the first list, and then returns a list of zeroes and ones, such that K[i] = 1 if L[i] is found within the list M.

Here is the code I have created so far:

def doSomething(L,M):
    K=[]
    x=0
    for i in range(len(L)):
        if L[i]==M[x]:
            K.append(1)
            x=x 1
        else:
            K.append(0)
    return K
L=[2,17,12,5,66,20,7]
M=[2,12,66]
print(doSomething(L,M))

The output I am expecting is [1, 0, 1, 0, 1, 0, 0] However I get an error in the 5th line of code: "IndexError: list index out of range"

Any help would be much appreciated.

CodePudding user response:

This should work:

K = [1 if x in M else 0 for x in L]

Or as a function:

def doSomething(L, M):
    return [1 if x in M else 0 for x in L]

CodePudding user response:

The error in line 5 was due to the fact that length of list M is less than that of L.

If you are still not comfortable using list comprehension as suggested by Ilia, you may use following code (updated doSomething):

def doSomething(L,M):
    K=[]
    for i in range(len(L)):
        if L[i] in M:
            K.append(1)
        else:
            K.append(0)

    return K
  • Related