Hal Lawrence Hal Lawrence - 15 days ago 4x
Python Question

Consecutive values?

Learning python, but having trouble telling function to find consecutive locations with same values. When I run the code, there's no errors but gives out the incorrect output. Suggestions on what to change?

def same_values(xs):
same = False
for i in (xs):
if xs == xs[1:]:
same = True
return same
same_values('Misses') # This should return as true


So you are looking for a consecutive pair in the list and returning true if you find one.

def same_values(xs):
    for i in range(len(xs)-1):
        if xs[i] == xs[i+1]:
            return True
    return False

>>> same_values('misses')
>>> same_values('mises')

Would give you the correct answer.
However python has a powerful iterator algebra. The advantage of this is that it would work with iterators (iterators don't generally support len()) as well as lists:

import itertools as it

def same_values(xs):
    a, b = it.tee(xs)
    next(b, None)
    return any(x == y for x, y in zip(a, b))

This pattern is described in the itertools recipes as pairwise:

import itertools as it

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = it.tee(iterable)
    next(b, None)
    return zip(a, b)

def same_values(xs):
    return any(x == y for x, y in pairwise(xs))

For example to check if any 2 consecutive lines in a file are the same (this wouldn't work with the list version):

with open('somefile') as f: