add treereduce function
authorLuke Kenneth Casson Leighton <lkcl@lkcl.net>
Tue, 26 May 2020 12:36:09 +0000 (13:36 +0100)
committerLuke Kenneth Casson Leighton <lkcl@lkcl.net>
Tue, 26 May 2020 12:36:09 +0000 (13:36 +0100)
src/nmutil/util.py

index e0b09af164c27b6dd64c32e8cc6402ce0a647db4..28a8e13621fef0efb454f3624a8b4adf2942f275 100644 (file)
@@ -8,3 +8,15 @@ def flatten(v):
             yield from flatten(i)
     else:
         yield v
+
+# tree reduction function.  operates recursively.
+def treereduce(tree, op, attr="data_o"):
+    #print ("treereduce", tree)
+    if not isinstance(tree, list):
+        return tree
+    if len(tree) == 1:
+        return getattr(tree[0], attr)
+    if len(tree) == 2:
+        return op(getattr(tree[0], attr), getattr(tree[1], attr))
+    s = len(tree) // 2 # splitpoint
+    return treereduce(op(tree[:s], op, attr), treereduce(tree[s:], op, attr))