Issue
I am trying to print the output of the for loop given below in a list but I get the following results:
import math
S= [(1,2),(3,4),(-1,1),(6,-7),(0, 6),(-5,-8),(-1,-1),(6,0),(1,-1)]
p,q = 3,-4
dist = []
for x,y in S:
dist=[]
cos_dist = math.acos((x*p + y*q)/((math.sqrt(x**2 + y**2))*(math.sqrt(p**2 + q**2))))
dist.append(cos_dist)
print(dist)
Here, the output is :
[2.0344439357957027]
[1.8545904360032246]
[2.9996955989856287]
[0.06512516333438509]
[2.498091544796509]
[1.2021004241368467]
[1.4288992721907328]
[0.9272952180016123]
[0.14189705460416438]
But I want it to be:
[2.0344439357957027,1.8545904360032246,2.9996955989856287,0.06512516333438509,2.498091544796509,1.2021004241368467,1.4288992721907328,0.9272952180016123,0.14189705460416438]
I have tried using
print(','.join(dist))
but it says
TypeError: sequence item 0: expected str instance, float found
How do I get the output I want?
Solution
First, move the dist
initialization outside of the loop.
Then you must convert floating-point numbers to strings before joining them, either in the loop:
dist.append(str(cos_dist))
Or after the loop:
print(','.join(map(str, dist)) )
Overall, list comprehension is a better tool for list construction:
dist = [math.acos((x*p + y*q) / ((math.sqrt(x**2 + y**2))\
*(math.sqrt(p**2 + q**2)))) for x,y in S]
Answered By - DYZ Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.