Skip to content

Instantly share code, notes, and snippets.

@Joeccp
Last active January 4, 2024 04:32
Show Gist options
  • Save Joeccp/f84b6056f2504f531ec812693612fec9 to your computer and use it in GitHub Desktop.
Save Joeccp/f84b6056f2504f531ec812693612fec9 to your computer and use it in GitHub Desktop.
Python find element index in N-D array
from typing import *
from operator import eq
def find_in_nd_array(array: Iterable,
value: Any,
function: Callable[[Any, Any], bool] = eq,
__prefix_indexes: tuple[int, ...] = tuple()
) -> tuple[int, ...]:
"""
Find the index of a value in an n-dimensional array.
>>> find_in_nd_array([1, 2, 3, 4, 5], 3)
(2,)
>>> find_in_nd_array([1, 2, 3, 4, 5], 99)
()
>>> find_in_nd_array([1, 1, 1, 1, 1], 1)
(0,)
>>> find_in_nd_array([[1, 2, 3], [4, 5, 6]], 3)
(0, 2)
>>> find_in_nd_array([[1, 2, 3], [4, 5, 6]], 99)
()
>>> find_in_nd_array([1, [2, 3], 4, 5], 2)
(1, 0)
>>> find_in_nd_array([[[1, 2], []], [[3], []]], 3)
(1, 0, 0)
>>> find_in_nd_array([1, [2, 3], 4, 5], 3, function=lambda x, y: x > y)
(2,)
>>> find_in_nd_array([1, [2, 3], 4, 5], None, function=lambda x, _: x == 4)
(2,)
"""
index_tuple: tuple[int, ...] = ()
for index, element in enumerate(array):
if isinstance(element, Iterable):
new_index_tuple: tuple[int, ...] = find_in_nd_array(element, value, function=function, __prefix_indexes=__prefix_indexes + (index,))
if new_index_tuple:
return new_index_tuple
else:
if function(element, value):
index_tuple = (__prefix_indexes + (index,))
print(index_tuple)
return index_tuple
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment