
The Angles of a Triangle
You are given the lengths for each side on a triangle. You need to find all three angles for this triangle. If the given side lengths cannot form a triangle (or form a degenerated triangle), then you must return all angles as 0 (zero). The angles should be represented as a list of integers in ascending order. Each angle is measured in degrees and rounded to the nearest integer number (Standard mathematical rounding).
Input: The lengths of the sides of a triangle as integers.
Output: Angles of a triangle in degrees as sorted list of integers.
原题链接: http://www.checkio.org/mission/triangle-angles/
题目大义: 已知三角形三边长, 求出各个角度, 如果无法构成一个三角形返回[0, 0, 0]
思路: 余弦定理
import math def checkio(a, b, c):
rel = [0, 0, 0]
if a + b > c and a + c > b and b + c > a:
rel[0] = int(round(math.degrees(math.acos(float(a**2 + b**2 - c**2) / float(2 * a * b)))))
rel[1] = int(round(math.degrees(math.acos(float(a**2 + c**2 - b**2) / float(2 * a * c)))))
rel[2] = int(round(math.degrees(math.acos(float(b**2 + c**2 - a**2) / float(2 * b * c))))) rel = sorted(rel) return rel
当然, 如果求出前两个角之后, 最后一个角可以通过180 - rel[0] - rel[1]得到; 若首先对a, b, c进行排序, 也可以进一步优化程序
import math def checkio(a, b, c):
edge = sorted([a, b, c]) if edge[0] + edge[1] <= edge[2]:
return [0, 0, 0] rel = [0, 0, 0]
rel[0] = int(round(math.degrees(math.acos(float(edge[2]**2 + edge[1]**2 - edge[0]**2) / float(2 * edge[2] * edge[1])))))
rel[1] = int(round(math.degrees(math.acos(float(edge[2]**2 + edge[0]**2 - edge[1]**2) / float(2 * edge[2] * edge[0])))))
rel[2] = 180 - rel[0] - rel[1] return rel