Reputation: 151
Convert the following while loop into a for loop. Your code should be written so that the return statement does not need to be altered. You are allowed to change the code before the while loop proper. string_list is a list of string that contains at least 15 instances of the string
'***'
j=0
while i<15:
if string_list[j] ='***':
i +=1
j +=1
return j
I tried doing this first it says while i<15
and i = i+1
so i know i ranges from (0...15) not including 15 so basically we will have like i = range(15)
so we will have something like:
for i in range(15):
I don't know what that j
is doing there.
Upvotes: 1
Views: 16876
Reputation: 362557
I will assume you meant to write string_list[j] == '***'
instead of string_list[j] ='***'
. I will also assume i
is initialised to 0
.
i, j = 0, 0
while i < 15:
if string_list[j] == '***':
i += 1
j += 1
return j
The first step is to understand what the loop is actually doing. It is iterating through string_list
elements, and every time an '***'
is encountered, i
is incremented. The loop will terminate when i
reaches 15
, and since a precondition was given that string_list
contains at least 15 copies of '***'
we do expect the loop should terminate.
When the loop terminates, i
will be equal to 15
and j
will simply have counted the number of elements in the list up until this point.
So to start you off, you could try iterating like this:
for s in string_list:
if s == `***`:
# keep track of how many times this has happened
# break if you've seen it happen 15 times
j += 1
return j
Upvotes: 4
Reputation: 304137
j = [i for i,x in enumerate(string_list) if x=='***'][15]
return j
lazy version inspired by comments from Peter and astynax
from itertools import islice
j = next(islice((i for i,x in enumerate(string_list) if x=='***'), 15, None))
return j
Upvotes: 2