【发布时间】:2011-12-29 20:10:58
【问题描述】:
我想知道这样做的一种相当“常见”或正常的方式是什么。并不是真的在寻找最短的答案,比如 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
【问题讨论】:
-
请尝试用文字描述所有这些应该做什么。它非常密集。
-
如果这工作正常,这对codereview.stackexchange.com来说可能是一个更好的问题
-
对不起密度。它读取一系列数字,例如。 '3 0 5 5 1 5 1 6 8' 并且必须找到第一个重复的数字序列,在本例中为 '5 1 5 1',并打印出该单个序列('5 1')。编辑:也是的,这可行,但我想必须有更好的方法----输入文本文件:2 0 6 3 1 6 3 1 6 3 1 ----输出6 3 1----- -
-
为什么不打印('5')?它应该打印 longest 序列吗?只有长度 > 2 的序列?
-
yeah - # 如果序列没有被破坏并且至少有 2 个成员 ----if ok and len(seq) > 1:---- 必须至少有 2 个成员.. . 我猜 1 个数字并不是真正的序列
标签: python numbers sequence cycle