Today I Learned
[내일배움캠프_데이터분석]3주차 금요일 TIL _ for 문
journal201
2024. 7. 12. 20:46
A. 어떤 문제가 있었는지
- 딕셔너리는 인덱싱이 안되었다.
- for문을 사용하였지만 player_positins 리스트 각각의 결과가 나오지 않고 값 한개만 출력되었다.
B. 내가 시도해본 것
player_positions = {
"John Doe": [(0, 0), (1, 1), (2, 2), (5, 5)],
"Jane Smith": [(2, 2), (3, 8), (6, 8)],
"Mike Brown": [(0, 0), (3, 4), (6, 8)]
}
def calculate_total_distances(player_positions):
name = player_positions.keys()
for i in name:
spot = list(player_positions[i])
for j in range(len((spot))):
x1= spot[j-1][0]
x2= spot[j][0]
y1= spot[j-1][1]
y2= spot[j][1]
distance = (((x1-x2)**2) + ((y1-y2)**2))**(1/2)
distance += distance
break
return distance
result=calculate_total_distances(player_positions)
print(result)
출력값: 8.48528137423857
C. 어떻게 해결했는지
import math
def calculate_total_distances(player_positions):
for player, positions in player_positions.items():
total_distance = 0.0
for i in range(1, len(positions)):
x1, y1 = positions[i - 1]
x2, y2 = positions[i]
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
total_distance += distance
print(f"{player}의 총 누적 이동 거리: {total_distance:.2f} 미터")
# 선수별 위치 데이터
player_positions = {
"John Doe": [(0, 0), (1, 1), (2, 2), (5, 5)],
"Jane Smith": [(2, 2), (3, 8), (6, 8)],
"Mike Brown": [(0, 0), (3, 4), (6, 8)]
}
# 총 누적 이동 거리 계산 실행
calculate_total_distances(player_positions)
# 실행 결과
# John Doe의 총 누적 이동 거리: 7.07 미터
# Jane Smith의 총 누적 이동 거리: 9.08 미터
# Mike Brown의 총 누적 이동 거리: 10.00 미터
D. 무엇을 새롭게 알았는지
- for문에 변수 지정을 1개 이상 할 수 있다.
- 디버깅을 하면 코드 흐름을 따라가며 오류 수정이 가능하다.