Search code examples
pythonarraysreturniteration

How to return true after finding every nth element for all elements


I'm trying to get every nth element in an array, but the function stops iterating due to the return true statement.

Here is my code:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

def get_nth(n, array):
    iterable_found = 0
    for i in range(len(array)):
        print(i)

        if i == (iterable_found + n):
            iterable_found += n
            
            return True
            
    return False


>>> print(get_nth(5, numbers))
0
1
2
3
4
5
True

But I want it so it goes through the rest of the array and returns true for 10 and 15. I plan on running this function through a while loop so I can actively get every nth element that is added. Thank you for any help.

Minimal example:

Csv file with numbers being streamed to it from websocket

1
2
3
...

function call

import np
array = np.genfromtxt('feed.csv', delimiter = ',')

# loop for checking

while True:
    print(get_nth(5, array))

Solution

  • I hope this helps , this works by returning the last position the function left off when returning and picks up from there when it called again with the last position.

    import random
    
    numbers = [3, 7, 3, 111, 222, 333, 4444, 555, 9, 10, 11, 12, 13, 14, 15]
    
    
    def get_nth(n, array, startPos):
        for x in range(startPos, len(array)):
            print(array[x])
            if (array[x] % n) == 0:
                return True, x
        return False
    
    
    pos = 0
    while True:
        if pos < len(numbers):
            result, pos = get_nth(3, numbers, pos)
            print(result)
            pos += 1
    
        # Works when adding numbers into the numbers list in the loop
        # or your case your websocket
        numbers.append(random.randint(0, 999))
    

    Output

    8
    True
    983
    615
    True
    479
    735
    True
    155