检测数字序列中的重复循环(python)
我想知道这样做的一个相当“普通”或正常的方式是什么。我并不是真的在寻找最短的答案,比如说一条2字线或者其他什么。我刚刚快速地将这段代码组合在一起,但我不觉得其中有太多内容。 此外,如果有任何图书馆可以帮助这一点,那将是非常好的检测数字序列中的重复循环(python),python,numbers,sequence,cycle,Python,Numbers,Sequence,Cycle,我想知道这样做的一个相当“普通”或正常的方式是什么。我并不是真的在寻找最短的答案,比如说一条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
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
def get_循环(行):
nums=line.strip().split(“”)
#2个主回路,用于x和y
对于范围(2,len(nums))中的x:#(从2开始,假设序列至少需要2个成员)
对于范围(0,x)内的y:
#如果x在它前面的数字中已经存在
如果nums[x]==nums[y]:
seq=[nums[x]#(重新)启动序列
加法器=1#(重新)将加法器设置为1
ok=True 35;(重新)将ok设置为True
#当序列仍然匹配(正常)且
#y的尾部尚未到达x的起点
当ok和y+加法器1:
打印(''.join(seq))#打印出来,用空格隔开
返回
您的问题实际上是“x:x+k中的所有项目是否与y:y+k中的项目匹配”。也就是说,一个k长度子集是否在一行中出现两次
你希望x:x+k与y:y+k不重叠。实现这一点的简单方法是将y定义为x加上一些偏移量d。如果您确信k我可能没有正确理解这一点,但我认为使用正则表达式有一个非常简单的解决方案
(.+ .+)( \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 1 5 1 6 8'
的扩展解释:
最初将匹配整个字符串,但将放弃结束字符,因为(.+.+)
将失败,此回溯将发生,直到(\1)+
无法匹配字符串开头,此时正则表达式引擎将在字符串中向前移动并重试(.+)
- 这将发生在捕获组从第二个5开始之前,它将在最后放弃字符,直到捕获
,此时正则表达式正在为'5 1'
查找任意数量的(\1)+
,它当然会找到这一点,匹配将成功'5 1'
(.+。+)
我认为这将始终找到正好两组1个或多个字符,组之间用一个空格字符分隔。然后(\1)+
部分将匹配它后面的任意数量的两件式组,这就是为什么我仍然不知道它如何匹配631631