Hi all,

I am trying to rewrite the following code, to avoid having to write 60 individual loops,I would really appreciate your help with this.

# Long Version - not ideal
num = 60

n = [open('n%i.txt' % i, "w") for i in range (num)]

for a2s1, a2s0, a1s1, a1s0 in zip(c2v1.values, c2v0.values, c1v1.values, c1v0.values):
    m = sqrt((((a2s1.data-a2s0.data)**2))+((a1s1.data**2-a1s0.data)**2))
    n[2].write(('%6.20f\n') % (m))
for a2s1, a2s0, a1s1, a1s0 in zip(c2v2.values, c2v1.values, c1v2.values, c1v1.values):
    m = sqrt((((a2s1.data-a2s0.data)**2))+((a1s1.data**2-a1s0.data)**2))
    n[1].write(('%6.20f\n') % (m))
:
for a2s1, a2s0, a1s1, a1s0 in zip(c2v60.values, c2v59.values, c1v60.values, c1v59.values):
    m = sqrt((((a2s1.data-a2s0.data)**2))+((a1s1.data**2-a1s0.data)**2))
    n[60].write(('%6.20f\n') % (m))

# Way of improving the code above (my attempt)
num = 60
n = [open('n%i.txt' % i, "w") for i in range (num)]

for i in range(num)
    for a2s1, a2s0, a1s1, a1s0 in zip(c2v(i+1).values, c2v(i).values, c1v(i+1).values, c1v(i).values):
        m = sqrt((((a2s1.data-a2s0.data)**2))+((a1s1.data**2-a1s0.data)**2))
        n[i+1].write(('%6.20f\n') % (m))

Is there anything wrong with the code, or could I improve this?

Thanks

Recommended Answers

All 3 Replies

m = sqrt((((a2s1.data-a2s0.data)2))+((a1s1.data2-a1s0.data)**2))

This look like same as math.hypot function. for at line 21 is missing :, you could consider preparing deltas before writing

I think you should also close the files, even if it is not strictly required in Python. 60 files is anyway lot to leave hanging around waiting for automatic closing by the interpreter. with block is guaranteed to do so.

Looks like you are using the files only one at the time so you could use single filehandle for them all, instead of the list. I have not your functions to test, but this should be quite close to correct.

num = 60
for i in range(num):
    with open('n%i.txt' % i, "w") as current:
        for a2s1, a2s0, a1s1, a1s0 in zip(c2v(i+1).values, c2v(i).values, c1v(i+1).values, c1v(i).values):
            deltas = a2s1.data-a2s0.data, a1s1.data**2-a1s0.data
            current.write('%6.20f\n' % math.hypot(*deltas))

Look kind of strange that you have a1s1.data also squared, hope your formula is correct.

Thanks pyTony! I will give that a try. Yes you are right that was a typo with the extra squared. By the way whats the significance of the 'star' within the math.hypot function. I couldn't see it mentioned in the docs http://docs.python.org/2/library/math.html

Thanks again

The star is used to unpack the two values as two individual parameters the hypot requires.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.