Friday, October 7, 2022

[FIXED] How can I write an additional piece of code to add all my outputs together?

Issue

So I wrote this code that returns the mean of the first three rows of a file.

import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))

and I correctly get the output, which is

100.177647525
97.27899259
100.2046613525

now I want to write an additional block of code that will add the outputs of this code together, in other words, I would like to add 100.177647525, 97.27899259 and 100.2046613525 together. I tried to do this by writing this up..

import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))
s = 0
for x in statistics.mean(h):
    s += x
print(s)

but I'm getting an error message saying "TypeError: 'float' object is not iterable". so what changes should I make to make this work?


Solution

You need to store the values in a variable or may be append a list with all the values like below: ####Solution 1: Store values in a list####


import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    sum_list = []
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))
        sum_list.append(statistics.mean(h))
    total = sum(sum_list)
print(total) 

####Solution 2: keep adding the value to a variable####


import statistics
with open('data/normal_distribution.csv','r') as f:
    g = f.readlines()[0:3]
    count = 0
    total = 0
    for x in g:
        q = str(x)
        l = q.split(',')
        m = list((l[:8]))
        h = [float(r) for r in m]
        print((statistics.mean(h)))
        count = statistics.mean(h)
        total = total + count
print(total)

I didn't run these codes yet but I think they should work.



Answered By - PandasasPD
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.