Hacker News new | ask | show | jobs
by MawKKe 46 days ago
Would be nice to have some example code how the class is intended to be used
1 comments

I was having a bit of trouble understanding the specifics of how to use it as well so while trying to replicate the sum example I ended up with this. but the whole thing is so clunky I am sure I am holding it wrong.

    def example_sum():
        def sum_empty():
                return 0
        def sum_unit(value):
                return value
        def sum_combine(agg_a, agg_b):
                return agg_a + agg_b
        def sum_finalize(agg):
                return agg

        sum_agg = two_stack_agg(sum_empty, sum_unit, sum_combine, sum_finalize)
        w_size = 4
        entry_values = list(range(1, 11) )
        trim_flag = False
        i = 0
        print(agg_sum.eval(), agg_sum.cum_aggs, agg_sum.values)
        agg_sum.push(entry_values[i])
        i += 1
        while agg_sum.len() > 0:
                if i < len(entry_values):
                        agg_sum.push(entry_values[i])
                        i += 1
                if trim_flag:
                        agg_sum.pop()
                elif agg_sum.len() >= w_size:
                        trim_flag = True
                print(agg_sum.eval(), agg_sum.cum_aggs, agg_sum.values)
result:

    0 [] []
    3 [] [1, 2]
    6 [] [1, 2, 3]
    10 [] [1, 2, 3, 4]
    14 [5, 9, 12, 14] []
    18 [5, 9, 12] [6]
    22 [5, 9] [6, 7]
    26 [5] [6, 7, 8]
    30 [] [6, 7, 8, 9]
    34 [10, 19, 27, 34] []
    27 [10, 19, 27] []
    19 [10, 19] []
    10 [10] []
    0 [] []
So a four window aggregate you push values and pop it when greater than the window size. I used the length(being the len of values + len cum_agg ) to measure the window size, but you could just count.

Most of the clunk was to get the same full fill/drain behavior as the example, probably unneeded on real data. The rest of the clunk is because I tend to write simple clunky python. and I stored the provided agg functions in the agg class.