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.
for i in xs:
if ii = True
elif ii = False
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==x])
Or, directly, without copying
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==x])
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==x])