[Python]_온도 단위 바꾸기

hanseungjune·2022년 6월 10일
0

Python

목록 보기
12/38

풀이

# 화씨 온도에서 섭씨 온도로 바꿔 주는 함수
def fahrenheit_to_celsius(fahrenheit):
    # 코드를 입력하세요.
    celsius = round(((fahrenheit - 32) * 5) / 9, 1)
    return celsius

temperature_list = [40, 15, 32, 64, -4, 11]
celsius_list = []
i = 0

while i < len(temperature_list):
    celsius_list.append(fahrenheit_to_celsius(temperature_list[i]))
    i += 1

print("화씨 온도 리스트: {}".format(temperature_list))  # 화씨 온도 출력
print("섭씨 온도 리스트: {}".format(celsius_list))  # 섭씨 온도 출력

풀기는 풀었는데 코드가 좀 지저분해져서 모범답안과의 비교를 하게 되었다.
모범답안은 기존의 temperature_list 배열의 요소를 수정하는 식으로 문제를 해결했기 때문에, 나 처럼 새롭게 배열을 만들어내야하는 귀차니즘을 방지하였다. 그래서 모범답안 코드가 비교적 깔끔하게 나온 것으로 보인다.

def fahrenheit_to_celsius(fahrenheit):
    return (fahrenheit - 32) * 5 / 9


temperature_list = [40, 15, 32, 64, -4, 11]
print("화씨 온도 리스트: {}".format(temperature_list))  # 화씨 온도 출력

# 리스트의 값들을 화씨에서 섭씨로 변환하는 코드
i = 0
while i < len(temperature_list):
    temperature_list[i] = round(fahrenheit_to_celsius(temperature_list[i]), 1)
    i += 1
print("섭씨 온도 리스트: {}".format(temperature_list))  # 섭씨 온도 출력

하지만 기존의 자료를 건드린다는 위험요소(?)를 방지하기 위해서 celsius_list 를 새로 만들어서 진행했다. 지금 당장의 문제는 간단해보여서 수정할 수 있겠지만, 만약에 길어진다면 풀이과정이 엄청 꼬일 것으로 생각해서 만들었다.

profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글