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.
>Solution :
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()