Checking if a sequence has consecutive identical characters
<p>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, <code>neighboring_twins(1,2,1,4,1)</code> should return <code>False</code> while <code>neighboring_twins(1,2,3,3,5)</code> should return <code>True</code> because there are two identical characters directly next to each other (the two 3's). </p>

<p>This is the code I have so far. I don't think having Python search for <code>"ii"</code> 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.</p>

<pre><code>def neighboring_twins(xs):

    for i in xs:
        if ii = True
            return True
        elif ii = False
            return False
</code></pre>

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

<p>The <code>pairwise</code> function from <a href="https://docs.python.org/2/library/itertools.html#recipes" rel="nofollow">itertools' recipies</a> will return a list of pairs of consecutive items. From here on, you're just a list comprehension away of what you need:</p>

<pre><code>from itertools import tee, izip
def pairwise(iterable):
    "s -&gt; (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]])
</code></pre>

<p>Or, directly, without copying <code>pairwise</code>:</p>

<pre><code>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]])
</code></pre>

<p><strong>EDIT:</strong><br/>
You could achieve the same functionality without using itertools, albeit with some performance degradation:</p>

<pre><code>def neighboring_twins(xs):
    return any([x for x in zip(xs, xs[1::]) if x[0]==x[1]])
</code></pre>

python loops character sequence