From d2314e56d9d52221b26fbc6de5758a27fc522af2 Mon Sep 17 00:00:00 2001 From: Luke Kenneth Casson Leighton Date: Tue, 26 May 2020 13:36:09 +0100 Subject: [PATCH] add treereduce function --- src/nmutil/util.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/nmutil/util.py b/src/nmutil/util.py index e0b09af..28a8e13 100644 --- a/src/nmutil/util.py +++ b/src/nmutil/util.py @@ -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)) -- 2.30.2