Rafael Madriz
Rafael Madriz

Reputation: 51

Sum float numbers from a list

I have a list of numbers which were taken from a file.

fh = open(<filename>)
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    num = float(line[20 : ])
    print(num)

Output:

0.6178
0.6961000000000001
0.7565
0.7625999999999999
0.7556
0.7002
0.7615

I have to sum all of them and take the average ("I can't use sum()"). I tried looping through all of them with 'for', to then sum and get the average with / operator; but I get the following error 'float' object is not iterable.

What I tried:

fh = open(<filename>)
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    num = float(line[20 : ])
    for n in num: 
        n = n + n  
    print(n)

With this a get the error of 'float' object is not iterable.

Also I tried adding the numbers to an array too see if can loop in an array but that didn't work for me either.

Upvotes: 1

Views: 279

Answers (4)

ABC
ABC

Reputation: 645

I think you need a variable outside the loop, for example:

fh = open(<filename>)

numbers = []
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    num = float(line[20 : ])
    # save num into a list for later use
    numbers.append(num)

# perform calculations 
total = 0
for num in numbers:
    total += num
average = total / len(numbers)

The issue with your code is that num is a float, which you can not loop through.

Upvotes: 3

Andreas B
Andreas B

Reputation: 42

You could also write it like this given your problem. But you might have to change some bits because your formulation seems a bit unclear to me.

`

fh = open("text.txt")
sum=0
n=0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    sum+=float(line[20:])
    n+=1
print("Sum:",sum)
print("Average",sum/n)

`

Upvotes: 0

Madar
Madar

Reputation: 247

Here is a simple solution

fh = open(<filename>)
total = 0 
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    num = float(line[20 : ])
    total += n 
print(total)

Upvotes: 0

mandulaj
mandulaj

Reputation: 763

You need to accumulate the sum into a variable in your for loop over the lines. You also have to count the number of lines. You can do that in your code like this:

fh = open(<filename>)
sum_num = 0 # Initialize the sum to 0
count = 0 # Initialize the counter of lines to 0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    num = float(line[20 : ])
    sum_num += num # Add your number to the sum
    count += 1 # Add 1 to your counter of lines
    print(num)

print(sum_num) # Print the sum
print(sum_num/count) # Print average which is just the sum divided by the number of lines

Upvotes: 0

Related Questions