I am learning Python 3. I have two lists:
A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]
If A and B have any items common, a third list should return them (with their index in B).
[1, 4, 3, 2, 0]
I am getting the below error,
Line 6: IndexError: list index out of range
Code:
class Solution:
def anagramMappings(self, A, B):
result =[]
for i in A:
for j in B:
if A[i]==B[i]:
result.append(j)
return result
Edit: Thanks for the answers. I figured out the below solution. It works for most test cases except this,
Input:
[40,40]
[40,40]
Output:
[0,0,0,0]
Expected:
[1,1]
Code:
class Solution:
def anagramMappings(self, A, B):
result =[]
for i in A:
for j in B:
if i==j:
result.append(B.index(j))
return result
if A[i]==B[i]:should beif A[i]==B[j]:`for i in A:will have the value 12 for the 1st iteration, which is more than the length of list A. Hence, the error. You will needif i == jinstead. Of course, this can be simplified by using python idioms.for var=i; i < len(list); i++) compared tofor i in list(enumeration where item is returned instead of index). See list iteration and list comprehension.