How do I add the sum of the squares in the input file?
Input file is a txt file and is shown below:
10 9 8 7 1 2 3 4
3 -4 1 -2
0.743 -12.3 5.3333 3
-3.3
Hence the output may look like this;
324.0
30.0
189.28613789000002
10.889999999999999
I can't add the floating numbers using sum as it displays an error, so any help would be much appreciated.
Here is my code:
#Ask the user to input a file name
file_name=input("Enter the Filename: ")
#Opening the desired file to read the content
infile=open(file_name,'r')
#Importing the math library
import math
#Iterating for the number of lines in the file
for line in infile:
#Converting the file to a list row by row
line_str=line.split()
for element in range(len(line_str)):
line_str[element]=float(line_str[element])
line_str[element]=math.pow(line_str[element],2)
total=sum(line_str[0:len(element)])
print(total)