python-checkio/Alice/humpty-dumpty.py

35 lines
1.3 KiB
Python

import math
def checkio(height, width):
return [round(calculate_volume(height, width), 2), round(calculate_area(height, width), 2)]
def calculate_area(height, width):
r_width = width / 2
r_height = height / 2
if r_width == r_height:
return 4 * math.pi * math.pow(r_width, 2)
return calculate_area_c_less_than_a(r_width, r_height) if height <= width else calculate_area_c_more_than_a(r_width, r_height)
def calculate_area_c_less_than_a(r_width, r_height):
e = math.sqrt(1 - (math.pow(r_height, 2) / math.pow(r_width, 2)))
return 2 * math.pi * math.pow(r_width, 2) + math.pi * (math.pow(r_height, 2) / e) * math.log((1 + e) / (1 - e))
def calculate_area_c_more_than_a(r_width, r_height):
e = math.sqrt(1 - (math.pow(r_width, 2) / math.pow(r_height, 2)))
return 2 * math.pi * math.pow(r_width, 2) * (1+(r_height/(r_width*e))*math.asin(e))
def calculate_volume(height, width):
return (4 * math.pi / 3) * math.pow(width / 2, 2) * (height / 2)
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(4, 2) == [8.38, 21.48], "Prolate spheroid"
assert checkio(2, 2) == [4.19, 12.57], "Sphere"
assert checkio(2, 4) == [16.76, 34.69], "Oblate spheroid"