Home > Blockchain >  is there a way to check for the first match element when comparing two arrays without using loops in
is there a way to check for the first match element when comparing two arrays without using loops in

Time:11-02

I have this grid array which contains numbers from 0 to 7. A slot can be considered free on the grid only if it is a 0 and there's no different number before it:

[0, 0, 0, 0, 1, 0, 0, 0]           # every 0 before the 1 is a free slot

I want to make it so that the program can find the first slot that contains a number from 1 to 7, so that it knows that all the previous slots are free. I can make it work using a loop, like:

array = [0, 0, 0, 0, 1, 0, 0, 0]
freeslot = len(array)-1               # initializing in case it does not find a match
for n in range(1, 8):
   if (n in array) and (array.index(n)-1 < freeslot):
         freeslot = array.index(n)-1

The thing is, whenever I'm running this to check the grid, I check for 15 different arrays, so I feel that a loop makes it too slow. Is there a way to make it not using loops, or at least make it more efficient?

CodePudding user response:

This should work. freeslot = list(map(lambda x: True if 7 >= x > 0 else False, array)).index(True). Basically what it does is replace everything in a array list copy that is less than 7 but over 1 and replaces it with True. Then it indexes the first case of True in the new copy.

CodePudding user response:

A possible solution is to use a numpy array and have a look at this solution: Numpy first occurrence of value greater than existing value

CodePudding user response:

ans = len(arr) - 1

for i, v in enumerate(arr):
    if v > 0:
        ans = i - 1
        break

ans
# 3
  • Related