0

My teacher told my class to do this homework:

Given a list of values pi ∈ R3 = {xi, yi, zi} in the file m.txt, write a program that calculates m = {mx, my, mz} = Σi pi / N ∈ R3, where N is the number of values read. The file is in CSV format, a value of pi per line, with values separated by commas".

Now my file is like this:

12.5, 45.1, 23.1
4.2, 2.0, 6.5
12.7, 48.5, 34.0

and i tried doing something like this:

f = open("m.txt", "r")

sx = 0.0
sy = 0.0
sz = 0.0

for i in f:
    p = i.split(",")
    px = p[0]
    py = p[1]
    pz = p[2]
    sx = sx + float(px)
    mx = sx / len(px)
    sy = sy + float(py)
    my = sy / len(py)
    sz = sz + float(pz)
    mz = sz / len(pz)

print [mx,my,mz]

but when i run the program, it considers not the lenght of the string, but the lenght of the value of the string. Can you help me doing this homework without using any arrays? Thanks in advance!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • `len(px)` is the length of the string from the file. That's not the same thing as the number of values read from the file. – Martijn Pieters Nov 11 '15 at 18:23
  • Perhaps you wanted to calculate the number of *lines* in the file instead? Keep a counter as you read the file perhaps? – Martijn Pieters Nov 11 '15 at 18:24
  • 2
    It looks like you want to increment a counter to count the number of lines input, then, *outside the loop*, divide each sum by the count. – Tom Zych Nov 11 '15 at 18:26
  • Duplicate http://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array?rq=1 –  Nov 11 '15 at 18:27
  • Not sure what you think the `len()` function does, but it most likely does **not** do what you think it does. `len(s) - Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).` –  Nov 11 '15 at 18:29
  • how do i keep a counter as i read the file? – Fabio Savelli Nov 11 '15 at 18:44
  • @FabioSavelli Do you still need help with this? – davejagoda Nov 18 '15 at 21:16

0 Answers0