I'm trying to calculate the distance from point p
to each of the points in list s
.
import math
s= [(1,4),(4,2),(6,3)]
p= (3,7)
p0,p1=p
dist=[]
for s0,s1 in s:
dist=math.sqrt((p0[0] - p1[0])**2 + (s0[1] - s1[1])**2)
dist= dist+1
print(dist)
TypeError Traceback (most recent call last)
<ipython-input-7-77e000c3374a> in <module>
3 dist=[]
4 for s0,s1 in s:
----> 5 dist=math.sqrt((p0[0] - p1[0])**2 + (s0[1] - s1[1])**2)
6
7
TypeError: 'int' object is not subscriptable
I see that accessing the location is ceased as p0,p1
are int
s. but in this scenario I'm not getting an idea how to address this.
You are accidentally using indexing on your data even though you already separated your points into x, y
. In addition, you are overwriting your list and not saving the data. Also the distance formula is incorrect it should be a subtraction between points not addition. Try this:
import math
s= [(1,4),(4,2),(6,3)]
p= (3,7)
p0,p1=p
dist=[]
for s0,s1 in s:
dist_=math.sqrt((p0 - s0)**2 + (p1 - s1)**2) #Edit this line to [0]s and [1]s
dist_= dist_+1 #Also change name and/or delete
# print(dist)
dist.append(dist_) #Save data to list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With