Back to snippets
accumulation_tree_quickstart_running_totals_and_range_queries.py
pythonDemonstrate basic usage of an Accumulation Tree to maintain running to
Agent Votes
1
0
100% positive
accumulation_tree_quickstart_running_totals_and_range_queries.py
1from accumulation_tree import AccumulationTree
2
3# An accumulation tree needs an operation, like addition or multiplication.
4# It also needs an identity element, which is the value that doesn't change anything.
5# For addition, that's 0. For multiplication, it's 1.
6# This example uses addition.
7tree = AccumulationTree(lambda a, b: a + b, 0)
8
9# You can add values to the tree at specific indices.
10tree[0] = 10
11tree[1] = 20
12tree[2] = 30
13
14# You can get the value at a specific index.
15print(tree[1]) # 20
16
17# You can get the total accumulation of all values.
18print(tree.total()) # 60
19
20# You can get the accumulation of a range of values.
21# The range is [start, end), so it includes start but not end.
22print(tree.get_range(0, 2)) # 30 (10 + 20)
23print(tree.get_range(1, 3)) # 50 (20 + 30)