Baron_Samedi
Baron_Samedi

Reputation: 565

How can I test two int lists in Python against each other for similarities and if the similarities indexes are in equivilant order throughout?

Below is a condensed version of what i have done so far. I feel I am very close to fix this. I get an output telling me that "ValueError: 0 is not in list"

la = [] # list a
lb = [] # list b`

for i in range(len(la)):
    for j in range(len(lb)):
        if lb[j] in la and lb.index(j) >= la.index(i): #THIS LINE!!!
            print ("yes")
        else:
            print ("no") 

Thanks in advance and beyond!

Upvotes: 0

Views: 45

Answers (2)

chapelo
chapelo

Reputation: 2562

With the clarifications you made of your requirements, consider the following:

A = [1, 2, 3, 4, 5]
B = [3, 8, 5, 6, 7]

prev_idx_a = 0  # you need a way to check if indexes in list A increment each time
for idx_b, b in enumerate(B):
    if b in A:
        idx_a = A.index(b)
        if idx_a > prev_idx_a:  # make sure the order is not inverted
            prev_idx_a = idx_a  
        else:
            print("No") # or return a -1, raise an exception, etc...

There is no output if the check is successful, only if it fails.

Now, consider that there could be duplicates, even when preserving the order:

A = [1, 2, 3, 4, 5]
B = [3, 8, 3, 5, 6, 7]

All the "3" come before the "5", but the code above will fail. You'd need to add another condition to test only the first occurrence:

prev_idx_a = 0
prev_b = None
for idx_b, b in enumerate(B):
    if b in A:
        if b != prev_b:  # check only first occurrence
            prev_b = b
            idx_a = A.index(b)
            if idx_a > prev_idx_a:
                prev_idx_a = idx_a
            else:
                print("No")

Upvotes: 0

Vikash Singh
Vikash Singh

Reputation: 14001

Your code has a bug in line

lb.index(j) >= la.index(i)

here j is index which starts with 0. lb.index(j) means you are looking for 0 in array lb. Which when not present will give you the error you have shared ValueError: 0 is not in list.

Probably you are looking for something like this.

la = [1] # list a
lb = [1] # list b`

for i in range(len(la)):
    for j in range(len(lb)):
        if lb[j] in la and j >= i:
            print ("yes")
        else:
            print ("no") 

Upvotes: 1

Related Questions