codeeval_challenges / 005_DetectingCycles /

# On CodeEval, test cases are read in from a file which is the first argument to your program
# Open the file and read in line by line. Each line represents a different test case
# (unless given different instructions in the challenge description)

import sys

def detect_cycle(sequence):
    """ Detect cycles of numbers in the sequence.
        Returns None when no cycle is detected
    sequence = sequence.split()

    for sample_idx in range(len(sequence)-3):
        sample = sequence[sample_idx:sample_idx+2]

        for match_idx in range(sample_idx+2, len(sequence)-1):
            match = sequence[match_idx:match_idx+2]

            if sample == match:
                sample = sequence[sample_idx:match_idx]
                match = sequence[match_idx:match_idx+len(sample)]

                if sample == match:
                    return ' '.join(sample)
    return None

test_cases = open(sys.argv[1], 'r')

for test in test_cases:
    # ignore test if it is an empty line
    # 'test' represents the test case, do something with it
    test = test.strip()

    if test != '':
        cycle = detect_cycle(test)
        if cycle is not None:
            print cycle