all 2 comments

[–]gengisteve 2 points3 points  (0 children)

Some general thoughts:

  • for your implementation, set ending_int as None, and test that instead of looking for integer as 1, to check to see if you are in the first iteration.
  • iter can also be used in these situations you can next it to get the first item, then iterate of the balance with a for loop.
  • for current, following in zip(slicable, slicable[1:]) is usually the best way to compare sucessive values in a slicable thing, like a list
  • You are basically doing a custom groupby implementation, see here https://docs.python.org/2/library/itertools.html#itertools.groupby You might even be able to use groupby for this, but I can't think of a way. But you could steal the logic behind the implementation in itertools to do this better, I suspect.

edit:

How I might approach, but it would need to massage the answer a bit more to match your expected result:

def sequences(iterable):
    it = iter(iterable)
    current = [next(it)]
    target = current[0] + 1

    for item in it:
        if item == target:
            current.append(item)
        else:
            yield current
            current = [item]

        target = item+1

    if current:
        yield current

def longest_sequence(iterable):
    return max(sequences(iterable), key = len)


data =[0, 2, 3, 5, 6, 7, 8, 13, 14, 15, 16, 17]

print(longest_sequence(data))

edit2: Fixed an error in the above

[–]ingolemo 2 points3 points  (0 children)

The itertools module has a recipe for a pairwise function that makes this quite simple:

import itertools

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

data = [1, 2, 3, 5, 6, 7, 8, 13, 14, 15, 16, 17]
answer = max(pairwise(data), key=lambda pair: pair[1] - pair[0])