가독성을 위한 리팩터링
길고 복잡한 함수를 더 작은 단위로 나누면 가독성과 모듈성이 모두 좋아집니다. 이번 연습에서는 하나의 함수를 더 작은 단위 함수들로 리팩터링해 보겠습니다. 아래에 리팩터링할 함수가 나와 있어요. 참고로, 연습에서는 지면 관계상 docstring을 사용하지 않지만, 실제 애플리케이션에서는 반드시 문서를 포함해야 합니다!
def polygon_area(n_sides, side_len):
"""Find the area of a regular polygon
:param n_sides: number of sides
:param side_len: length of polygon sides
:return: area of polygon
>>> round(polygon_area(4, 5))
25
"""
perimeter = n_sides * side_len
apothem_denominator = 2 * math.tan(math.pi / n_sides)
apothem = side_len / apothem_denominator
return perimeter * apothem / 2
이 연습은 강의의 일부입니다
Python으로 배우는 소프트웨어 공학 원칙
연습 안내
perimeter를 계산하는 로직을polygon_perimeter함수로 옮기세요.- 컨텍스트에 나온 로직을 옮겨
polygon_apothem함수의 정의를 완성하세요.math모듈은 이미 임포트되어 있습니다. - 새로 만든 단위 함수를 활용해
polygon_area의 정의를 완성하세요. - 더 잘 쪼갠
polygon_area를 사용해 변의 길이가 10인 정육각형의 넓이를 계산하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
def polygon_perimeter(n_sides, side_len):
return ____
def polygon_apothem(n_sides, side_len):
denominator = ____
return side_len / denominator
def polygon_area(n_sides, side_len):
perimeter = ____
apothem = ____
return perimeter * apothem / 2
# Print the area of a hexagon with legs of size 10
print(____(n_sides=6, side_len=10))