Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created August 29, 2020 17:56
Show Gist options
  • Save vlad-bezden/2abdb544e1ffe66827f0b8cdf8ee79a5 to your computer and use it in GitHub Desktop.
Save vlad-bezden/2abdb544e1ffe66827f0b8cdf8ee79a5 to your computer and use it in GitHub Desktop.
Calculate shape of the list of any dimension using recursion
from typing import List, Tuple, Union
def shape(ndarray: Union[List, float]) -> Tuple[int, ...]:
if isinstance(ndarray, list):
# More dimensions, so make a recursive call
outermost_size = len(ndarray)
row_shape = shape(ndarray[0])
return (outermost_size, *row_shape)
else:
# No more dimensions, so we're done
return ()
three_d = [
[[0, 0, 0], [1, 1, 1], [2, 2, 2]],
[[0, 0, 0], [1, 1, 1], [2, 2, 2]],
[[0, 0, 0], [1, 1, 1], [2, 2, 2]],
[[0, 0, 0], [1, 1, 1], [2, 2, 2]],
[[0, 0, 0], [1, 1, 1], [2, 2, 2]],
]
result = shape(three_d)
print(result)
# (5, 3, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment