In the first code below (Using for loop) When I want to skip 2 index by increasing the index within the body of for loop, it ignores i = i 2
and updates the index only with for i in range (len(c))
phrase, while in the c we could do this in th e body of for loop by for (int i = 0 ; i <sizeof(c) ;i ){i = 2;}
. Is there anyway to implement this using a for loop (by correcting first code) or I have to use a while loop (second code)?
First Code (For loop)
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)
Second Code (While Loop)
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)
CodePudding user response:
You can use continue
to skip. You'll just need a condition that will be True
.
def jumpingOnClouds(c):
skipCondition = False
count_jumps = 0
for i in range (len(c)):
if skipCondition:
skipCondition = False
continue
if (i 2 <len(c) and c[i] == 0 and c[i 2] ==0):
count_jumps =1#It doesnt let me to update i in the while loop
skipCondition = True
continue
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)
Putting continue
will continue iterating, but before that, it will make the skipCondition = True
. The next iteration, skipCondition
will be True
, so you will skip again, but setting skipCondition
back to False