[Python] Is there an elegant way to check if index can be requested in a numpy array?

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I am looking for an elegant way to check if a given index is inside a numpy array (for example for BFS algorithms on a grid).

    The following code does what I want:

    import numpy as np

    def isValid(np_shape: tuple, index: tuple):
    if min(index) < 0:
    return False
    for ind,sh in zip(index,np_shape):
    if ind >= sh:
    return False
    return True

    arr = np.zeros((3,5))
    print(isValid(arr.shape,(0,0))) # True
    print(isValid(arr.shape,(2,4))) # True
    print(isValid(arr.shape,(4,4))) # False


    But I'd prefer something build-in or more elegant than writing my own function including python for-loops (yikes)

    Continue reading...

Compartilhe esta Página