+ 7
Why am I getting IndexError: list index out of range?
I have tried to create a program that determines the number of consecutive ones (1) in a list. So I defined a variable j = 1, which will start checking for 1 from the second element in the list and compare it with i, which starts checking from the first element. So for example if the second element = the first element = 1, then the count will change from 0 to 1, as two consecutive elements (the first and the second) are equal to 1. https://code.sololearn.com/czdo9Qk2cLk1/?ref=app
18 Respostas
+ 4
To count the number of consecutive ones Ipang
+ 4
Ipang Yes you're right
+ 4
Crunk I respectfully disagree... Final j is len(seq) - 1 and not len(seq) + 1.
(I've shown that in my following code...)
https://code.sololearn.com/cU8ZdGnsAk5x/?ref=app
But yeah, your solution code works.
+ 4
Crunk That's because we put print(' ') statement at different places... I put it before j += 1 and you put it after j +=1... That's why your j will start from 2 and end at 6.
+ 3
Atul I changed the indentation as per your recommendation, but now the output is 0 instead of 2...
https://code.sololearn.com/c3J9HXftkgU3/?ref=app
+ 3
Atul Well he said there are two consecutive 1s in the list... That's why output should be 2
https://code.sololearn.com/c3J9HXftkgU3/?ref=app
+ 2
[0, 0, 1, 1, 1, 0]
Here we have 2 consecutive ones right? just want confirmed ...
Index 2 and 3
Index 3 and 4
+ 2
The program is run sequently,and when the while loop is complete,the rest of the program is run,which means the final j is len(seq)+1,and then the rest of the code is run.len(seq)+1 is obviously out of the index range of seq.
You can try this:
def count11(seq):
count =0
for i in range(1,len(seq)):
if seq[i]==seq[i-1]==1:
count+=1
return count
+ 2
Srihari Srihari 200 Yeah... Copy.
+ 1
What is your goal Rahul Hemdev
Search or count?
+ 1
Rahul Hemdev oh sorry,it's my fault.but you are not right either.final j is len(seq).The code should look like this
https://code.sololearn.com/cfdcPylWh5YH/?ref=app
+ 1
Rahul Hemdev But your code doesn't output the last j,because when j is6,the code inside the while loop doesn't execute, so that the final j is 6.
- 3
svg
- 3
vdGdaetx,. fdxydvdcwtozmdhtddsd