Cootie234 Cootie234 - 1 year ago 107
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 =

xs = [2,1,2]

output =

xs = []


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download