Find the perimeter of the polygon
The task looks like this:
But maybe I'm doing something wrong, can you tell me?
from math import *
a = []
while True:
a.append(int(input()))
len = 0
n = len(a) / 2
print(n)
for i in range(1, n):
sum = (a[i] - a[i - 1]) ** 2
len += sum
i += 1
print(sqrt(l))
2 answers
Right?
def len_seg(x1,y1,x2,y2):
return ((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))**0.5
x = []
y = []
while True:
try:
x.append(int(input()))
y.append(int(input()))
except EOFError:
break
x.append(x[0])
y.append(y[0])
perimetr = 0
n = len(x)
for i in range(0, n-1):
perimetr += len_seg(x[i],y[i],x[i+1],y[i+1])
print(perimetr)
The main thing is that it is easier to work with x
and y
separately. And then everything is simple - we look for the length of each segment and sum it up. Adding a starting point to the end of the array as well.
You do not process half of the coordinates at all, and the ones that you process - you sum up the strange value (x-y)**2
...
Try to extract the square root of each term of the sum. You seem to have forgotten it.
If that doesn't help, then the recipe is below.
First, you need to sort the points by the polar angle, since they can be set in a different order. And then, in the order of traversal, counterclockwise, for example.
Imagine that one of the points lies on the x (M) axis, the other point is P. Polar angle -- fi. Now, let M := P. Take it the next point.
Full example :
So you need to iterate over [A1, A2, A3, A4, A5, A6, A7]. Note that if at some point, you choose the wrong sequence, you can get, for example, in addition to the perimeter, also [A5, A1].
To calculate the polar angle, you can use the scalar product. There are several useful functions and tasks here.