Python to bin calculated results from a function

Question:

A function is defined to perform some calculation (in this example, it’s to sum). The calculated result is to be put into bins (of each 10 as an interval, such as <10, 10-19, 20-29 etc).

What is the smart way to do so?

I have a dump way, which created a dictionary to list all the possible calculated results and their bins:

def total(iterable):
    dict = {36: '30 - 40' , 6 : '< 10'}
    total = dict[sum(iterable)]
    return total



candidates = [[11,12,13],[1,2,3]]

for iterable in candidates:
    output = str(total(iterable))
    print (output)
Asked By: Mark K

||

Answers:

Using a dict will not be feasible, since you possibly cannot have all the options over there, here is how you can do it

candidates = [[11,12,13], [1,2,3]]

for iterable in candidates:
    sum1 = sum(iterable)
    start_bin = int(sum1/10) * 10
    end_bin = start_bin + 10
    print('{} - {}'.format(start_bin, end_bin))

You can also make variations in the size of bin by changing how the values are multiplied and divided

Answered By: Prityush bansal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.