【发布时间】:2022-01-03 03:08:14
【问题描述】:
在下面的第一个代码中(使用 for 循环)当我想通过增加 for 循环主体内的索引来跳过 2 个索引时,它会忽略 i = i+2 并仅使用 for i in range (len(c)) 短语更新索引,而在c++ 我们可以通过for (int i = 0 ; i <sizeof(c) ;i++){i += 2;} 在 for 循环体中执行此操作。无论如何要使用 for 循环(通过更正第一个代码)来实现这一点,还是我必须使用一个 while 循环(第二个代码)?
第一个代码(For 循环)
def jumpingOnClouds(c):
count_jumps = 0
for i in range (len(c)):
if (i+2 <len(c) and c[i] == 0 and c[i+2] ==0):
i = i+2
count_jumps+=1#It doesnt let me to update i in the while loop
elif (i+1 <len(c) and c[i] == 0 and c[i+1] ==0):
count_jumps+=1
else:
pass
return(count_jumps)
c = [0, 0, 0, 1, 0, 0]
jumpingOnClouds(c)
第二个代码(While 循环)
def jumpingOnClouds(c):
count_jumps = 0
i = 0
while( i < len(c)):
if (i+2 <len(c) and c[i] == 0 and c[i+2] ==0):
i = i+2
count_jumps+=1
elif (i+1 <len(c) and c[i] == 0 and c[i+1] ==0):
count_jumps+=1
i = i+1
else:
i = i+1
return(count_jumps)
c = [0, 0, 0, 1, 0, 0]
jumpingOnClouds(c)
【问题讨论】: