From: Luke Kenneth Casson Leighton Date: Tue, 26 May 2020 12:36:09 +0000 (+0100) Subject: add treereduce function X-Git-Tag: 24jan2021_ls180~57 X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=d2314e56d9d52221b26fbc6de5758a27fc522af2;p=nmutil.git add treereduce function --- 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))