0

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
3
  • For starters: if A[i]==B[i]: should be if A[i]==B[j]: ` Commented Jan 21, 2018 at 18:50
  • 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 need if i == j instead. Of course, this can be simplified by using python idioms. Commented Jan 21, 2018 at 18:50
  • 1
    See what python offers in terms of constructs especially when you are coming from other language. i.e. index based array iteration (for var=i; i < len(list); i++) compared to for i in list (enumeration where item is returned instead of index). See list iteration and list comprehension. Commented Jan 21, 2018 at 18:58

2 Answers 2

3

You are iterating over the elements and not the indices of A & B.

The line: for i in A will iterate over the list and return 12,28.. and similar output will be for the B list as well.

But you are supposed to iterate i and j over the indices, so you get their length by len(A) and len(B) and then convert it into an iterable by using python's range function. Your code should be like:

  class Solution:
        def anagramMappings(self, A, B):
            result =[]
            for i in range(len(A)):
                for j in range(len(B)):
                    if A[i]==B[j]:
                            result.append(j)
            return result
Sign up to request clarification or add additional context in comments.

Comments

1

The python for loop iterates over the elements, not the indicies. So the if statement on first hit is evaluating to A[12] == B[50], which I don't think you want here. Try if i == j instead.

Comments

Your Answer

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