I have a long list which consist of two fixed possible numbers (0 and 1). e.g:
JavaScript
x
2
1
l = [0,0,0,0,0,1,1,1,1,1,1,1]
2
I don’t know which number occurs first in the list but I am sure that if 0 is occurring first in the list then it will occur consecutively followed by 1, same case for 1.
I am performing some kind of action on the basis of these number conditions (0,1) but also I need to show a message before the first occurrence of 0 and 1.
First occurrence of first number (in this case 0), I have managed like this.
JavaScript
1
5
1
if l[0] == 0:
2
print ('first occurrence of 0')
3
elif l[0] == 1:
4
print ('first occurrence of 1')
5
I am not sure how to point out first occurrence of 1 during execution of this list.
For this example list I need result like this.
JavaScript
1
15
15
1
msg before first occurrence of 0
2
0
3
0
4
0
5
0
6
0
7
msg before first occurrence of 1
8
1
9
1
10
1
11
1
12
1
13
1
14
1
15
Advertisement
Answer
A solution that works for more than just 0 and 1 can be based to a set
containing the elements we encountered so far:
JavaScript
1
8
1
l = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
2
s = set()
3
for x in l:
4
if x not in s:
5
print("first occurrence of %s" % x)
6
s.add(x)
7
print(x)
8
Result:
JavaScript
1
15
15
1
first occurrence of 0
2
0
3
0
4
0
5
0
6
0
7
first occurrence of 1
8
1
9
1
10
1
11
1
12
1
13
1
14
1
15