递归列表遍历

时间:2019-03-12 13:36:46

标签: python arrays list recursion traversal

我需要遍历一个列表。列表中的每个元素都是最大跳转。因此,如果我的起始位置为5,那么我可以在列表中最多跳转5个位置。但是,如果列表的第5个元素为0,则它​​是无效的跳转,因此我必须将跳转减少1。我想递归执行此操作,但每次都重复相同的数字。

def traverse(lst,pos,out):
    out.append(pos)
    try:
        while lst[pos] + pos == 0:
            pos = pos - 1
        pos += lst[pos]
        traverse(lst,pos,out)       
    except IndexError:
        print(out[:-1] + ['out'])

c2 = [3,5,1,2,5,1,4]
traverse(c2,c2[0],out)

output: [3, 5,'out']

c3 =  [3,5,1,0,5,1,4] #So i changed the 3th value to 0
traverse(c3,c3[0],out)

output:
 3,
 3,
 3,
 3,
 ...]

直到最大递归错误。为什么我的pos不降低价值?

1 个答案:

答案 0 :(得分:1)

while条件不能做正确的事情:

while lst[pos] + pos == 0:

您真的要检查列表中的值

while lst[lst[pos] + pos] == 0:

但是,当您减少pos时,仍然会遇到问题:突然您会看到一个不同的lst[pos],而实际上应该保持不变。

因此,首先 增加pos然后执行循环会更有用:

pos += lst[pos]       # move this here, before the loop
while lst[pos] == 0:  # corrected condition
    pos = pos - 1

如评论中所述,这不会阻止算法陷入困境。如果您跳到一个零值,而前面的值是1,那么您将一遍又一遍地跳到相同的零。

相关问题