-1

Here is what I have done:

seq = [0,1,1,1,0]
num = 0
for i in seq:
    if seq[i] == seq[i+1]:
        num = num+1
    else:
        continue
print(num)

I am expected to come up with the number of occurence of '11' in the sequence, i.e. '11' and '11' and the answer is saying 2.

mkrieger1
  • 10,793
  • 4
  • 39
  • 47
AbdRaheem
  • 1
  • 1
  • 3
    Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – mkrieger1 Mar 29 '21 at 14:08
  • You are iterating the list, `seq`, not the positions. You should use `for i, n in enumerate(seq):` where `i` is the index e.g. `0, 1, 2, 3, 4` and `n` is the number e.g. `0, 1, 1, 1, 0` – Alex Mar 29 '21 at 14:12
  • This is useful. Thanks – AbdRaheem Apr 01 '21 at 11:15

1 Answers1

0

To be able to use seq[i+1], you must stop one before the end of the sequence. In addition, you should use enumerate to access the index in the sequence as well as the value:

seq = [0,1,1,1,0]
nums = 0
for i, x in enumerate(seq[:-1]):
    if x == seq[i+1]:
        nums += 1
print(nums)
Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199