我想知道执行此操作的相当“常见”或正常的方式是什么。并不是真的在寻找最短的答案,例如 2-liner 或其他任何东西。我只是快速地将这段代码放在一起,但我总觉得里面的内容太多了。 另外,如果有任何库可以帮助解决这个问题,那就太好了。
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
最佳答案
我可能没有正确理解这一点,但我认为使用正则表达式有一个非常简单的解决方案。
(.+ .+)( \1)+
这是一个例子:
>>> regex = re.compile(r'(.+ .+)( \1)+')
>>> match = regex.search('3 0 5 5 1 5 1 6 8')
>>> match.group(0) # entire match
'5 1 5 1'
>>> match.group(1) # repeating portion
'5 1'
>>> match.start() # start index of repeating portion
6
>>> match = regex.search('2 0 6 3 1 6 3 1 6 3 1')
>>> match.group(1)
'6 3 1'
这是它的工作原理,(.+ .+)
将匹配至少两个数字(尽可能多)并将结果放入捕获组 1。(\1) +
将匹配一个空格后跟捕获组 1 的内容,至少一次。
以及对字符串 '3 0 5 5 1 5 1 6 8'
的扩展解释:
(.+ .+)
最初将匹配整个字符串,但会放弃末尾的字符,因为(\1)+
将失败,此回溯将发生直到(.+ .+)
无法匹配字符串的开头,此时正则表达式引擎将在字符串中向前移动并重试- 这会发生,直到捕获组从第二个 5 开始,它会在末尾放弃字符,直到捕获到
'5 1'
,此时正则表达式正在寻找任意数量的'5 1'
为(\1)+
,当然会找到这个,匹配成功
关于python - 检测数字序列中的重复循环(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8672853/