How can I get my code to iterate through the list?

Question:

The question is: For every five numbers in the following list from left to right, calculate the means of every five numbers. For example, the first five numbers are 2, 1, 3, 5, and 2, and the mean is 2.6

inputList = [2, 1, 3, 5, 2, 7, 3, 7, 4, 6, 9, 1, 0, 2, 4, 8, 9, 2, 0, 1, 3].

This is what I have so far:

inputList = [2, 1, 3, 5, 2, 7, 3, 7, 4, 6, 9, 1, 0, 2, 4, 8, 9, 2, 0, 1, 3]
for i in inputList:
    total = 0
    avg = 0
    for j in range(5):
        total = total + inputList[j]
        avg = total/5
    print(avg)

I’m able to get the mean of the first 5 elements on the list but I can’t get the code to keep going after that.

Asked By: Kay Ram

||

Answers:

If I understand your question correctly, you want to find the means of the rolling window of each 5-items?

Try this with more_itertools windowed():

from more_itertools import windowed

L = [2, 1, 3, 5, 2, 7, 3, 7, 4, 6, 9, 1, 0, 2, 4, 8, 9, 2, 0, 1, 3]

#list(windowed(L, 5))
#[(2, 1, 3, 5, 2), (1, 3, 5, 2, 7), (3, 5, 2, 7, 3), (5, 2, 7, 3, 7), (2, 7, 3, 7, 4), (7, 3, 7, 4, 6), (3, 7, 4, 6, 9), (7, 4, 6, 9, 1), (4, 6, 9, 1, 0), (6, 9, 1, 0, 2), (9, 1, 0, 2, 4), (1, 0, 2, 4, 8), (0, 2, 4, 8, 9), (2, 4, 8, 9, 2), (4, 8, 9, 2, 0), (8, 9, 2, 0, 1), (9, 2, 0, 1, 3)]

means = [sum(parts)/5 for parts in windowed(L, 5)]
print(means)
# [2.6, 3.6, 4.0, 4.8, 4.6, 5.4, 5.8, 5.4, 4.0, 3.6, 3.2, 3.0, 4.6, 5.0, 4.6, 4.0, 3.0]
Answered By: Daniel Hao
for j in range(5):
        total = total + inputList[j]

in this piece of code, you iterate over the same 5 elements over and over again i.e when i = 0

  • j = 0,
  • j = 1,
  • j = 2,
  • j = 3,
  • j = 4

then again when i = 1

  • j = 0,
  • j = 1,
  • j = 2,
  • j = 3,
  • j = 4

this continues i times.

what you should do is

inputList = [2, 1, 3, 5, 2, 7, 3, 7, 4, 6, 9, 1, 0, 2, 4, 8, 9, 2, 0, 1, 3]
for i in range(0,len(inputList)):
    if(i<=len(inputList)-5):
        print("starting from index " + str(i))
    total = 0
    avg = 0
    for j in range(i,i+5):
        if(i<=len(inputList)-5):
            print(inputList[j],end=" ")
            total = total + inputList[j]
            avg = total/5
    if(i<=len(inputList)-5):
        print("avg is " + str(avg))
        print()
Answered By: Bhavani
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.