您将获得正负整数的列表跳转,表示正向或负向跳跃。
从索引0开始,您跳转到索引0+jump[0]
。一般来说,如果你在索引k
,你会跳转到索引k+jump[k]
让我们说jumps[0]
是2。索引变为2.假设jumps[2]
为-1,索引将变为1。
编写函数list_jumps(jumps)
,其中jumps是上述列表。如果索引永远不会离开输入列表的边界,则函数应返回字符串'cycle'
,否则它必须返回'out-of-bounds'
。起始索引始终为0.
dm=[3,0,0,-2]
def list_jump(jumps):
xs=jumps
xy=jumps
max=len(xs)
while(True):
p = int(xs[0])
print p
for i in range (0,max,p):
print i,"iii"
p = xs[i]
if xs[i]=="visited":
return False
else:
xs[i]="visited"
print xs
return True
if list_jump(dm):
print "not cycle"
else:
print "cycle"
我真的不需要解决方案。我只是想知道错误是什么。
答案 0 :(得分:0)
请注意,我只需创建一个集合seen
并将每个索引添加到其中。
def list_jump(jumps):
i = 0
seen = {0}
while True:
try:
i += jumps[i]
if i < 0:
# negative indices are legal, but we should exit if we have one.
return "out-of-bounds"
except IndexError:
# we've escaped the list: non-cyclic!
return "out-of-bounds"
else:
if i in seen:
return "cycle"
else:
seen.add(i)