Please HELP!!
I have a list:
JavaScript
x
2
1
a = ['False', 'False', 'True', 'True', 'True', 'False', 'False', 'True', 'True']
2
I want to generate iteration number if it’s False the number continues and if it’s True the number stays. I Try this code:
JavaScript
1
11
11
1
result = []
2
x = 1
3
for i in a:
4
while i == 'False':
5
result.append(x)
6
if i == 'True':
7
x+=1
8
continue
9
result.append(x)
10
x += 1
11
it’s just keep running and did not show any output.
the desired output will be [1,2,3,3,3,4,5,6,6]
I have no idea what’s wrong with it Thanks
Advertisement
Answer
Yet another version of this (with the output behaving as required by OP):
JavaScript
1
11
11
1
def weird_sequence(some_list):
2
prev = None
3
number = 0
4
for item in some_list:
5
if prev is None:
6
prev = "False"
7
if item == "False" or prev == "False":
8
number += 1
9
yield number
10
prev = item
11
Usage:
JavaScript
1
3
1
>>> list(weird_sequence(['False', 'False', 'True', 'True', 'True', 'False', 'False', 'True', 'True']))
2
[1, 2, 3, 3, 3, 4, 5, 6, 6]
3