Home > database >  Checking for near appearances of items in two lists - Python
Checking for near appearances of items in two lists - Python

Time:11-14

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.

CodePudding user response:

indexes = [i for i,d in enumerate(list1) if d=='1']
distance = 2
count = 0
for i in a:
    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

CodePudding user response:

This should work:

ones = []
for i in range(len(list2)):
    if(list2[i] == '1'):
        ones.append(i)
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

  • Related