-3

Don't know how to name such pattern, but by examples I think it is easier to explain.

For example let say I have this list:

lst = [1, 2, 3, 5, 6, 7, 8, 10, 11, 15]

So Now I need to merge part of list that goes by increment of one (meaning only first and last items ar kept), but if there only two items in such increment, there is nothing to merge, because they are both first and last items of such pattern.

So by running some method that handles this, it should separate it in this:

merged = [(1, 3), (5, 8)]
original = [10, 11, 15]

Note on original list. It has those three items only, because 2, 6 and 7 are merged (they match that pattern). 10 and 11 goes by one increment, but there are only two numbers, so there is nothing to merge. And 15 does not match any pattern at all.

I thought of using some comparison of first and second items on iteration, but algorithm got complicated and I was not able to properly merge/detach those items.

P.S.

And the reason for this is I have a module that generates excel reports. And it is possible to specify formulas how some rows need to be computed (on excel side).

Now current functionality returns specific (when separate part of sheet are used in one formula) rows numbers. So for example formula could end up something like: "sum(A1, A2, A3, A5)". And if there lots of rows, actual expression could become very big. But if I could simplify it by having that same formula for exmaple "sum(A1:A3, A5)" it would not be so big.

Andrius
  • 19,658
  • 37
  • 143
  • 243
  • @UrielEli well I don't really have anything working to show, so I do not know how useful that would be, but I will provide something if you think that would help. – Andrius Nov 29 '16 at 14:58
  • Its interesting how guy from question http://stackoverflow.com/questions/2154249/identify-groups-of-continuous-numbers-in-a-list got 44 up votes and I got downvoted for not providing any sample code (though the case is the same on both questions). Is this some kind of double standards?:) – Andrius Nov 29 '16 at 15:31

1 Answers1

0

So my problem seems to be very similar to the one here (question was found by Chris_Rands): Identify groups of continuous numbers in a list

Though for completeness, here is modified version of an answer from that question that solved my problem:

from operator import itemgetter
from itertools import groupby

def merge_ranges(data):
    ranges = []
    origin = []
    for key, group in groupby(
            enumerate(data), lambda (index, item): index - item):
        group = map(itemgetter(1), group)
        if len(group) > 2:
            ranges.append((group[0], group[-1]))
        else:
            origin.extend(group)
    return ranges, origin
Community
  • 1
  • 1
Andrius
  • 19,658
  • 37
  • 143
  • 243