Advice on code structure to prevent duplication of code (Python, lists)
Question: The scenario at play is that I have an ordered list of items. I want to
convert that list into a single string.

However.

It's not simply a matter of converting each item into a string and
concatenating. I need to do some processing on the list as part of the
conversion.

Here's a rough example:

List:

    
    
    [1, 
     2,
     3,
     0,
     1,
     9,
     -4,
     3,
     2]
    

The output I desire would be this:

    
    
    The total of a group is 6.
    The total of a group is 10.
    The total of a group is 5.
    

Here's the code I've written that can do this:

    
    
    total = 0
    result = ""
    for item in myList:
        if (item <= 0):
            result += "The total of a group is %d.\n" % total
            total = 0
            continue
        total += item
    
    # NOTICE THE CODE DUPLICATION HERE...
    result += "The total of a group is %d.\n" % total
    
    print result
    

The problem is I have the `result +=` in the code _twice_. The reason for that
is that we have no guarantee that the last item in the list is an item that is
going to cause the code that actually appends the string to execute. (i.e. we
don't have any guarantee that it's a number 0 or less.)

The obvious solution to this might be "check the last item in the list and if
it's not <= 0 then add a 0 as the last item." This would work on a list of
primitives like this. It however would not work on a list of objects or
complex types, or if the comparison is more involved than simply <= 0.

So the question is: IS there a good way to structure this code such so that I
am not duplicating code, which of course introduces a huge possibility for
errors?

Thanks!

F


Answer: If you're allowed to you can use `itertools.groupby` to group positive
numbers, eg:

    
    
    from itertools import groupby
    
    data = [1, 2, 3, 0, 1, 9, -4, 3, 2]
    group_totals = [sum(g) for k, g in groupby(data, lambda L: L > 0) if k]
    for group_total in group_totals:
        print 'The sum of a group is', group_total
    print 'Total of all groups is', sum(group_totals)
    

