bogus
bogus

Reputation: 35

Checking for near appearances of items in two lists - Python

I'm writing this function where I have two lists composed of '1' and '0' and for every occurrence of a '1' in list1, I have to check if there's any '1' in list2 at a given distance from the one in list1.

Here's the function I made so you can understand better:

for i in range (len(list1)):
    if list1[i] == '1':
       if any ('1' == num for num in list2[i:i+distance+1]): 
          count += 1

I'm wondering if there's any faster way to do this or do something that starts with:

for '1' in list1:
     if any etc.

Upvotes: 0

Views: 116

Answers (2)

Alecs Fly
Alecs Fly

Reputation: 46

indexes = [i for i,d in enumerate(list1) if d=='1']
distance = 2
count = 0
for i in indexes:
    if '1' in list2[i:i+distance+1]:
        count += 1

This code is on average 1.5-2 times faster than yours. If we say about big array Results + tests with answer upper Res image

Upvotes: 1

atanay
atanay

Reputation: 174

This should work:

ones = [i for i,d in enumerate(list1) if d == '1']
cur = 0 # cursor pointing to the current one-location of list2 in the list "ones"
count = 0

for i in range(len(list1)):
    if(list1[i] != '1'):
        continue

    # we will advance the cursor until it is past the lower bound of the selection
    while(cur < len(ones) and ones[cur] < i - distance):
        cur += 1
    # if the cursor is out of bound we know that there are no more ones we are interested in inside list2 so we can exit the loop:
    if(cur == len(ones)):
        break
    if(ones[cur] <= i + distance):
        count += 1

Note: this approach's performance only depends on the size of the lists and not on the distance variable

Upvotes: 0

Related Questions