Good 'ol itertools.groupby to the rescue:
from itertools import groupby def contiguous(seq): return sum(1 for k,g in groupby(seq, lambda x: x is not None) if k) == 1
gives
>>> contiguous([1,2,3,None,None]) True >>> contiguous([None, 1,2,3,None]) True >>> contiguous([None, None, 1,2,3]) True >>> contiguous([None, 1, None, 2,3]) False >>> contiguous([None, None, 1, None, 2,3]) False >>> contiguous([None, 1, None, 2, None, 3]) False >>> contiguous([1, 2, None, 3, None, None]) False
[edit]
Since there are some discussions in the comments, I will explain why I like this approach better than some others.
We are trying to find out if there is one continuous group of objects other than None, and
sum(1 for k,g in groupby(seq, lambda x: x is not None) if k)
counts the number of adjacent objects other than None using the function in stdlib, which is designed to collect adjacent groups. As soon as we see groupby , we are considered "adjacent groups" and vice versa. In this sense, it is self-documenting. This is basically the definition of my goal.
IMHO The only weakness is that it does not close, and this can be fixed, but having thought about it, I still prefer it, because it uses a primitive that I like, "count the number of adjacent non-" No groups ", which I prefer to just "tell me if you have more than one continuous group different from the group" as soon as you can. "
Many of the approaches to implementing the latter depend on smart observation of the problem, for example, โif there is only one continuous group of no-No objects,โ then if we scan until we find the first no-No object, then scan the objects until until we find the first group other than None, if it exists, is there anything left that None gives us our answer. "(Or something like that, which is part of my problem: I have to think about it .) It seems to me that I am using the "implementation details" about the problem to solve it and the tricks uetsya problems properties that we can use to solve it rather than just give a problem in Python and let Python do the job.
I am a bear with a very small brain, as they say, and I like to avoid being smart, because, in my experience, the route is dotted with FAIL.
As always, each run can vary, of course, and is probably proportional to their skill.