Skip to content Skip to sidebar Skip to footer

Summing List Of Counters In Python

I am looking to sum a list of counters in python. For example to sum: counter_list = [Counter({'a':1, 'b':2}), Counter({'b':3, 'c':4})] to give Counter({'b': 5, 'c': 4, 'a': 1}) I

Solution 1:

The sum function has the optional start argument which defaults to 0. Quoting the linked page:

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total

Set start to (empty) Counter object to avoid the TypeError:

In [5]: sum(counter_list, Counter())
Out[5]: Counter({'b': 5, 'c': 4, 'a': 1})

Solution 2:

This version was faster in my experience. This is upper bound by O(log(n)).

defsum_counters(counter_list):

    '''
    Recursive counter with a O(log(n)) Complexity
    '''iflen(counter_list) > 10:

        counter_0 = sum_counters(counter_list[:int(len(counter_list)/2)])
        counter_1 = sum_counters(counter_list[int(len(counter_list)/2):])

        returnsum([counter_0, counter_1], Counter())

    else:

        returnsum(counter_list, Counter())

global_counter = sum_counters(counter_list)

Post a Comment for "Summing List Of Counters In Python"