Мне было интересно, какой способ сделать это будет довольно «обычным» или нормальным. На самом деле не искал кратчайшего ответа, такого как 2-строчный или что-то в этом роде. Я только что быстро собрал этот фрагмент кода, но я не могу не чувствовать, что его слишком много. Также, если есть какие-нибудь библиотеки, которые могут помочь с этим, это было бы очень хорошо.
def get_cycle(line):
nums = line.strip().split(' ')
# 2 main loops, for x and y
for x in range(2, len(nums)): # (starts at 2, assuming the sequence requires at least 2 members)
for y in range(0, x):
# if x is already in numbers before it
if nums[x] == nums[y]:
seq = [nums[x]] # (re)start the sequence
adder = 1 # (re)set the adder to 1
ok = True # (re)set ok to be True
# while the sequence still matches (is ok) and
# tail of y hasn't reached start of x
while ok and y + adder < x:
if nums[x + adder] == nums[y + adder]: # if next y and x match
seq.append(nums[x + adder]) # add the number to sequence
adder += 1 # increase adder
else:
ok = False # else the sequence is broken
# if the sequence wasn't broken and has at least 2 members
if ok and len(seq) > 1:
print(' '.join(seq)) # print it out, separated by an empty space
return