Cootie234 Cootie234 - 1 month ago 15
Python Question

How to find adjacent pairs in a sequence, python

For one of my assignments, I have to write a code that will look for adjacent pairs in a sequence. If there are no pairs in the sequence, the output has to be None. Could be a list, string, whatever. The code that I have only worked for half of the test files (the true ones), yet I am having trouble passing the false test files. I am not sure what I am doing wrong and would like help to complete this task. Here is the code I am working with:

def neighboring_twins(xs):
twins = False
for i in range(len(xs)):
for j in range(i+1,len(xs)):
if xs[i] == xs[j]:
twins = True
return twins


sample inputs:

xs = [1,1]


output =
true


xs = [2,1,2]


output =
False


xs = []


output=
False

Answer

Loop through xs starting from the second item, and compare to the previous item:

def neighboring_twins(xs):
    for i in range(1, len(xs)):
        if xs[i] == xs[i-1]:
            return True
    return False
Comments