1

I have a list of number:

a=[2,3,4,5,1,3,2,4,5,6,2,6,7,5,2,7,5,6,2]

I want the longest sequence that not contain 2, so the answer is:

[3,4,5,1,3]

How can I do this in python? Thanks for helping me,

1 Answer 1

3

You can use itertools.groupby():

from itertools import groupby

a = [2, 3, 4, 5, 1, 3, 2, 4, 5, 6, 2, 6, 7, 5, 2, 7, 5, 6, 2]

# get the subsequences not containing 2
subsequences = (list(it) 
                for contains_two, it in groupby(a, lambda x: x == 2)
                if not contains_two)

# find the longest one among them
print(max(subsequences, key=len))

prints

[3, 4, 5, 1, 3]
Sign up to request clarification or add additional context in comments.

5 Comments

That's why python is great! Many complex things can be done in one or two lines.
@jammon: If you add comments. Because the above code is almost incomprehensible. :)
@Lennart: You're right, this version is much, much better. I was just pondering on a solution to the question and had something with ifs and fors and some 5 to 10 lines in mind. Then I discovered this answer (and looked up itertools.groupby in the docs) and was once more baffled by the conciseness of a pythonic solution.
And comments now added, and the code is much more comprehensible. :)
@Lennart: I think the main reason the code is more readable is that I reformatted it and gave meaningful names to the variables. Thanks for the comments anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.