递归列表遍历

问题描述 投票:-3回答:1

我需要遍历一个列表。列表的每个元素都是最大跳跃。因此,如果我的起始位置是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减少价值?

python arrays list recursion traversal
1个回答
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,那么你将一遍又一遍地跳到同一个零。

© www.soinside.com 2019 - 2024. All rights reserved.