famguy74 famguy74 - 1 month ago 15
Python Question

Python - Checking if a sequence has consecutive identical characters

For this function I'm trying to have it return "True" when a sequence has consecutive identical characters and have it return "False" when a sequence doesn't. For example, neighboring_twins(1,2,1,4,1) should return False while neighboring_twins(1,2,3,3,5) should return True because there are two identical characters directly next to each other (the two 3's).

This is the code I have so far. I don't think having Python search for "ii" is the right way to do it as I keep getting syntax errors. I wasn't sure how I would instruct Python to search for consecutive identical characters but assumed I should use a for loop. Any help would be appreciated.

def neighboring_twins(xs):

for i in xs:
if ii = True
return True
elif ii = False
return False


Edit: I'd like to accomplish this without importing from other modules and in the simplest way possible.

Answer

The pairwise function from itertools' recipies will return a list of pairs of consecutive items. From here on, you're just a list comprehension away of what you need:

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

def neighboring_twins(xs):
    return any([x for x in pairwise(xs) if x[0]==x[1]])

Or, directly, without copying pairwise:

from itertools import tee, izip
def neighboring_twins(xs):
    a,b = tee(xs)
    next(b, None)
    return any([x for x in izip(a, b) if x[0]==x[1]])

EDIT:
You could achieve the same functionality without using itertools, albeit with some performance degradation:

def neighboring_twins(xs):
    return any([x for x in zip(xs, xs[1::]) if x[0]==x[1]])
Comments