소개
신비와 마법으로 가득 찬 매혹적인 해양 세계에서, 항해사들이 위험한 물길뿐만 아니라 마법의 비전 흐름까지 탐험하는 세계가 있습니다. 그곳에는 항해와 주문술 모두에서 뛰어난 기술을 가진 전설, 악명 높은 마법사 해적 선장 매젤란이 있습니다. 매젤란은 Python 의 Common Standard Libraries 를 활용하는 능력으로 경쟁 해적들을 따돌리고 숨겨진 보물을 발견하는 데 성공의 기반을 다졌습니다.
매젤란 선장의 선원으로서, 여러분의 임무는 일련의 도전을 헤쳐나가기 위해 동일한 강력한 Python 라이브러리 세트를 마스터하는 것입니다. 공해상에서 가장 두려운 배인 The Enchanted Marauder 의 운명이 여러분의 손에 달려 있습니다. Python 의 코드를 받아들여 매젤란 선장에게 없어서는 안 될 존재가 되겠습니까? 앞으로의 모험은 여러분의 기술과 지략을 똑같이 시험할 것입니다!
Math 및 Datetime 으로 탐색하기
이 단계에서는 앞으로의 여정을 위한 항로를 계획하는 임무를 맡게 됩니다. math 모듈을 사용하여 최적의 경로를 계산하고, datetime 모듈을 사용하여 도착 시간을 추정합니다.
먼저, ~/project 디렉토리에 chart_course.py라는 스크립트를 엽니다. 이 스크립트는 위도와 경도 좌표를 기반으로 다음 목적지까지의 거리를 계산합니다.
import math
## Coordinates of your current location and the destination (in degrees)
current_location = (0, 0)
destination = (10, 10)
def calculate_distance(loc1, loc2):
## Convert degrees to radians
lat1, lon1 = map(math.radians, loc1)
lat2, lon2 = map(math.radians, loc2)
## Haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
r = 6371 ## Radius of Earth in kilometers
return c * r
## Estimate the distance
distance = calculate_distance(current_location, destination)
print(f"The distance to the destination is {distance:.2f} kilometers.")
이제 datetime을 사용하여 도착 시간을 추정합니다.
from datetime import datetime, timedelta
## Assume an average ship speed of 10 km/h
average_speed = 10
## Calculate the time of arrival
time_to_destination = timedelta(hours=distance / average_speed)
arrival_time = datetime.now() + time_to_destination
print(f"Estimated time of arrival: {arrival_time.strftime('%Y-%m-%d %H:%M:%S')}")
터미널에서 다음 명령을 실행하여 스크립트를 실행합니다.
python ~/project/chart_course.py
다음 정보가 터미널에 표시되어야 합니다.
The distance to the destination is 1568.52 kilometers.
Estimated time of arrival: 2024-01-04 09:40:36
Collections 를 이용한 재고 관리
매젤란 선장은 Python 의 collections 모듈을 사용하여 재고를 정렬하고 접근 가능하게 유지합니다. 여러분의 임무는 collections 모듈의 Counter를 사용하여 선박의 보급품 데이터를 정리하는 것입니다.
~/project 디렉토리에 manage_inventory.py라는 스크립트를 엽니다.
from collections import Counter
## Inventory list
inventory = ['potion', 'dagger', 'potion', 'gold coin', 'gold coin', 'ruby']
inventory_counter = Counter(inventory)
## Display inventory count
for item, count in inventory_counter.items():
print(f"{item.title()}: {count}")
## Add items to your inventory
loot = ['gold coin', 'emerald', 'potion']
inventory_counter.update(loot)
print("\nUpdated inventory:")
for item, count in inventory_counter.items():
print(f"{item.title()}: {count}")
재고를 관리하려면 다음을 실행합니다.
python ~/project/manage_inventory.py
다음 정보가 터미널에 표시되어야 합니다.
Potion: 2
Dagger: 1
Gold Coin: 2
Ruby: 1
Updated inventory:
Potion: 3
Dagger: 1
Gold Coin: 3
Ruby: 1
Emerald: 1
요약
이 랩에서는 마법과 해상 모험의 세계로 이동했습니다. 우리는 Python 의 Common Standard Libraries 를 캡틴 매젤란이 항해에서 사용하는 도구와 유사하게, 과제를 해결하기 위한 도구로 활용하는 매력적인 시나리오를 설계했습니다. math와 datetime을 사용하여 지리적 계산을 수행하고, collections로 마법 아이템의 재고를 관리하는 방법을 배웠으며, 파일 시스템 및 기타 일반적인 작업에 추가적인 표준 라이브러리를 사용하여 작업하게 될 것입니다.
각 작업을 완료하면서 이러한 라이브러리 사용에 대한 숙련도를 높였을 뿐만 아니라, The Enchanted Marauder 의 성공적인 항해에도 기여했습니다. 이러한 연습은 창의성과 효율성으로 실질적인 문제를 해결할 수 있는, 효과적인 Python 프로그래머가 되기 위한 기반을 마련합니다. 지식의 바람이 여러분의 돛을 계속 채우기를 바랍니다!



