【Checkio Exercise】Three Point Circle

计算三角形外接圆的函数:

Three Point Circle

If we want to build new silos, then we need to make more formal and useful plots of land. Our topographer only marks a few points on the map and thinks that is good enough. It doesn't give us the coordinates which all our robots use, just a handwritten note. Paper notes! The nerve.

Through any three points that do not exist on the same line, there lies a unique circle. The points of this circle are represented in a string with the coordinates like so:

(x1,y1),(x2,y2),(x3,y3)

Where x1,y1,x2,y2,x3,y3 are digits.

You should find the circle for the three given points, such that the circle lies through these point and return the result as a string with the equation of the circle. In a Cartesian coordinate system (with an X and Y axis), the circle with central coordinates of (x0,y0) and radius of r can be described with the following equation:

(x-x0)^2+(y-y0)^2=r^2

Where x0y0r are decimal numbers rounded to two decimal points. Remove extraneous zeros and all decimal points, they are not necessary. For rounding, use the standard mathematical rules.

Input: Coordinates as a string.

Output: The equation of the circle as a string.

#答案
def circle_equation(note):
note = list(eval(note))
x1 = note[0][0]
x2 = note[1][0]
x3 = note[2][0]
y1 = note[0][1]
y2 = note[1][1]
y3 = note[2][1]
a = ((x3-x2)**2+(y3-y2)**2)**0.5
b = ((x3-x1)**2+(y3-y1)**2)**0.5
c = ((x1-x2)**2+(y1-y2)**2)**0.5
p = 0.5*(a+b+c)
s = (p*(p-a)*(p-b)*(p-c))**0.5
x = ((y2 - y1) * (y3 * y3 - y1 * y1 + x3 * x3 - x1 * x1) - (y3 - y1) * (y2 * y2 - y1 * y1 + x2 * x2 - x1 * x1)) / (
2 * (x3 - x1) * (y2 - y1) - 2 * ((x2 - x1) * (y3 - y1)));
y = ((x2 - x1) * (x3 * x3 - x1 * x1 + y3 * y3 - y1 * y1) - (x3 - x1) * (x2 * x2 - x1 * x1 + y2 * y2 - y1 * y1)) / (
2 * (y3 - y1) * (x2 - x1) - 2 * ((y2 - y1) * (x3 - x1)));
r = a*b*c/(4*s)
r = round(r, 2)
if x.is_integer():
x = int(x)
if y.is_integer():
y = int(y)
if r.is_integer():
r = int(r)
string = '(x-' + str(x) + ')^2+(y-' + str(y) + ')^2=' + str(r) + '^2'
return string

#调试结果
print(circle_equation("(2,2),(6,2),(2,6)"))
print(circle_equation("(3,7),(6,9),(9,7)"))
print(circle_equation("(2,2),(6,2),(2,6)") == "(x-4)^2+(y-4)^2=2.83^2")
print(circle_equation("(3,7),(6,9),(9,7)") == "(x-6)^2+(y-5.75)^2=3.25^2")

 

posted @ 2018-05-28 11:04  史达林之剑  阅读(247)  评论(0编辑  收藏  举报