Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading