Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First: dict of lambdas solution in Clear category for Simple Areas by ainoneko
import math
# Hoping that a,b,c form a valid triangle
# Otherwise, math.sqrt() may fail
def heron_area(a, b, c):
s = (a + b + c) / 2
return math.sqrt(s * (s - a) * (s - b) * (s - c))
def simple_areas(*args):
# Hoping that only 1, 2, or 3 params are passed
# Otherwise, {}.get(..., some-default-value) could be used
return round({
1: lambda d: math.pi * d**2 / 4,
2: lambda a, b: a * b,
3: lambda a, b, c: heron_area(a, b, c),
}[len(args)](*args), 2)
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
def almost_equal(checked, correct, significant_digits=2):
precision = 0.1 ** significant_digits
return correct - precision < checked < correct + precision
assert almost_equal(simple_areas(3), 7.07), "Circle"
assert almost_equal(simple_areas(2, 2), 4), "Square"
assert almost_equal(simple_areas(2, 3), 6), "Rectangle"
assert almost_equal(simple_areas(3, 5, 4), 6), "Triangle"
assert almost_equal(simple_areas(1.5, 2.5, 2), 1.5), "Small triangle"
July 17, 2021