-1

No imports allowed. I am writing a program for a simple moving average but keep getting an error.

inp = 12345
lst = [int(x) for x in str(inp)]
x = range (len(lst))
for n in x:
    An =((lst[n]+ lst[n+1])/2)  
    print(An)
    n+=1

I keep getting:

1.5
2.5
3.5
4.5

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-16-ea7ffe0bd993> in <module>
      4 for n in x:
      5     while n <= 5:
----> 6         An =((lst[n]+ lst[n+1])/2)
      7         print(An)
      8         n+=1

IndexError: list index out of range

I know it is because of the last[n+1] term but no matter what while conditions I have tried I cannot get around this simple error

ashbit_
  • 29
  • 8

2 Answers2

0

Replace x = range(len(lst)) with x = range(len(lst) - 1)

Torben545
  • 97
  • 1
  • 9
0

Because here:

inp = 12345
lst = [int(x) for x in str(inp)]
x = range (len(lst))
for n in x:
    An =((lst[n]+ lst[n+1])/2)  
                        ^
    print(An)
    n+=1

you are adressing a value outside the length of x. To solve this you can just add: -1 to x:

inp = 12345
lst = [int(x) for x in str(inp)]
x = range (len(lst)-1)
                    ^
for n in x:
    An =((lst[n]+ lst[n+1])/2)  
    print(An)
    n+=1
Jonas
  • 1,749
  • 1
  • 10
  • 18