Skip to content

Instantly share code, notes, and snippets.

@victor-iyi
Created April 10, 2018 11:04
Show Gist options
  • Save victor-iyi/9aa2968121e7f02caa67fc7b78139474 to your computer and use it in GitHub Desktop.
Save victor-iyi/9aa2968121e7f02caa67fc7b78139474 to your computer and use it in GitHub Desktop.
Traversing a nested list to estimate it's shape or dimension
# Shape = 2x3
a = [
[1, 2, 3],
[4, 5, 6]
]
# Shape = 2x3x2
b = [
[[1, 1], [2, 2], [3, 3]],
[[4, 4], [5, 5], [6, 6]]
]
# Shape = 3x3x3
c = [
[[1, 1, 1], [2, 2, 2], [3, 3, 3]],
[[4, 4, 4], [5, 5, 5], [6, 6, 6]],
[[7, 7, 7], [8, 8, 8], [9, 9, 9]],
]
class Vector():
def __init__(self, v):
self.v = v
def __repr__(self):
return str(self.v)
def __str__(self):
return repr(self)
def traverse(self, node):
"""Traverse a tree node."""
# Retrieve all the element in current node.
elements = self.getElements(node)
# Append the number of element in current node.
self._shape.append(len(elements))
# Check if any elements contains a node.
nodes = list(filter(self.isNode, elements))
# If there's any node.
if len(nodes) != 0:
# Loop through the nodes & continue traversal.
self.traverse(nodes[0])
@staticmethod
def isNode(element):
"""Determine if an element is a node or vertex.
Returns True if it's node & False otherwise.
"""
iterables = {list, tuple, set}
return type(element) in iterables
@staticmethod
def getElements(node):
"""Returns the element of a given node."""
return [element for element in node]
@property
def shape(self):
"""Retrieve the shape of current vector."""
# Start of with an empty shape.
self._shape = []
# Traverse the vector tree.
self.traverse(self.v)
return self._shape
if __name__ == '__main__':
vec_a = Vector(a)
vec_b = Vector(b)
vec_c = Vector(c)
print('{} = {}'.format('vec_a', vec_a))
print('{} = {}'.format('vec_b', vec_b))
print('{} = {}'.format('vec_c', vec_c))
print()
print('Shape for vec_a =', vec_a.shape)
print('Shape for vec_b =', vec_b.shape)
print('Shape for vec_c =', vec_c.shape)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment