Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[자동차 경주]소현우 과제 제출합니다. #1

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,27 @@ jun : -----
- **기능을 구현하기 전 `docs/README.md`에 구현할 기능 목록을 정리**해 추가합니다.
- **Git의 커밋 단위는 앞 단계에서 `docs/README.md`에 정리한 기능 목록 단위**로 추가합니다.
- [커밋 메시지 컨벤션](https://gist.github.com/stephenparish/9941e89d80e2bc58a153) 가이드를 참고하여 커밋 메시지를 작성합니다.


## 구현할 기능 목록
1. **자동차 이름 입력**
- 쉼표(`,`)로 구분된 자동차 이름을 입력
- 각 이름은 5자 이하로 제한 -> 넘으면 ValueError
- 중복된 이름은 제거

2. **시도 횟수 입력**
- 사용자로부터 경주 시도 횟수를 입력
- 입력값이 1 이상이어야 한다. -> 넘으면 ValueError
- 숫자가 아닌 값을 입력하면 -> ValueError

3. **자동차 경주 진행** (move_cars 함수로 구현)
- 각 자동차는 무작위 숫자를 받아 4 이상이면 한 칸 이동
- 이동 결과를 출력

4. **경주 상태 출력** (print_race 함수로 구현)
- 각 자동차의 현재 위치를 화면에 출력
- 자동차 이름 오른쪽에 이동한 거리를 `-`로 표시

5. **우승자 결정** (get_winners 함수로 구현)
- 가장 멀리 이동한 자동차를 우승자로 선정
- 여러 명이 동점일 경우, 공동 우승자로 처리
56 changes: 49 additions & 7 deletions src/racingcar/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,54 @@
""" 자동차 경주 게임 메인 스크립트 """

import random

def move_cars(car_positions):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

PEP8 스타일 가이드를 준수해야 합니다.

다음과 같은 스타일 문제를 수정해 주세요:

  • 함수 정의 사이에 빈 줄 2개가 필요합니다
  • 29번 줄이 최대 길이(79자)를 초과합니다
  • 45번 줄에 불필요한 공백이 있습니다
  • 변수 N은 snake_case 명명 규칙을 따라야 합니다
-def move_cars(car_positions):
+
+
+def move_cars(car_positions):

-def print_race(car_positions):
+
+
+def print_race(car_positions):

-def main():
+
+
+def main():

-    car_names = list(dict.fromkeys(name.strip() for name in car_names if name.strip()))
+    car_names = list(dict.fromkeys(
+        name.strip() for name in car_names if name.strip()
+    ))

-    N = int(input("시도할 횟수는 몇 회인가요? "))
+    num_attempts = int(input("시도할 횟수는 몇 회인가요? "))

-    for _ in range(N): 
+    for _ in range(num_attempts):

Also applies to: 11-11, 26-26, 29-29, 36-36, 45-45

🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 5-5: E302 expected 2 blank lines, found 1

"""자동차 이동 로직 (랜덤 숫자가 4 이상이면 이동)"""
for name in car_positions:
if random.randint(1, 9) >= 4:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

숫자상수는, 매직넘버상수로 바꾸고 전방선언 해주는 것이 좋습니다.

car_positions[name] += 1

def print_race(car_positions):
"""현재 경주 상태 출력"""
for name, pos in car_positions.items():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pos도 좋지만 position처럼 풀네임으로 작성하는 것도 고민해보세요.

if pos > 0:
print(f"{name} : {'-' * pos}")
else:
print(f"{name} : {' '}")
print()


def get_winners(car_positions):
"""최종 우승자 결정"""
max_pos = max(car_positions.values())
return [name for name, pos in car_positions.items() if pos == max_pos]

def main():
"""
프로그램의 진입점 함수.
여기에서 전체 프로그램 로직을 시작합니다.
"""
# 프로그램의 메인 로직을 여기에 구현
print("프로그램이 시작되었습니다.")
"""메인 함수"""
car_names = input("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분): ").split(",")
car_names = list(dict.fromkeys(name.strip() for name in car_names if name.strip()))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

PEP8 스타일 가이드를 준수해야 합니다.

파이프라인 검사에서 발견된 스타일 문제를 수정해야 합니다.

다음 사항들을 수정해 주세요:

  1. 36번 줄이 최대 길이(79자)를 초과합니다
  2. 43번 줄의 변수 N은 snake_case 명명 규칙을 따라야 합니다
  3. 52번 줄에 불필요한 공백이 있습니다
-    car_names = list(dict.fromkeys(name.strip() for name in car_names if name.strip()))
+    car_names = list(dict.fromkeys(
+        name.strip() for name in car_names if name.strip()
+    ))

-        N = int(input("시도할 횟수는 몇 회인가요? "))
+        num_attempts = int(input("시도할 횟수는 몇 회인가요? "))

-    for _ in range(N): 
+    for _ in range(num_attempts):

Also applies to: 43-43, 52-52

🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 36-36: line too long (87 > 79 characters)


for name in car_names:
if len(name) > 5:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

숫자상수는, 매직넘버상수로 바꾸고 전방선언 해주는 것이 좋습니다.

raise ValueError("⚠ 자동차 이름은 5자 이하만 가능합니다!")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

입력값 검증을 강화해야 합니다.

자동차 이름에 대한 추가 검증이 필요합니다:

  • 빈 입력 처리
  • 공백만 있는 이름 처리
  • 특수문자 포함 여부 검사
     car_names = input("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분): ").split(",")
+    if not car_names:
+        raise ValueError("⚠ 자동차 이름을 입력해주세요!")
     car_names = list(dict.fromkeys(name.strip() for name in car_names if name.strip()))
+    if not car_names:
+        raise ValueError("⚠ 유효한 자동차 이름이 없습니다!")
 
     for name in car_names:
+        if not name.isalnum():
+            raise ValueError("⚠ 자동차 이름은 알파벳과 숫자만 가능합니다!")
         if len(name) > 5:
             raise ValueError("⚠ 자동차 이름은 5자 이하만 가능합니다!")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
car_names = input("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분): ").split(",")
car_names = list(dict.fromkeys(name.strip() for name in car_names if name.strip()))
for name in car_names:
if len(name) > 5:
raise ValueError("⚠ 자동차 이름은 5자 이하만 가능합니다!")
car_names = input("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분): ").split(",")
if not car_names:
raise ValueError("⚠ 자동차 이름을 입력해주세요!")
car_names = list(dict.fromkeys(name.strip() for name in car_names if name.strip()))
if not car_names:
raise ValueError("⚠ 유효한 자동차 이름이 없습니다!")
for name in car_names:
if not name.isalnum():
raise ValueError("⚠ 자동차 이름은 알파벳과 숫자만 가능합니다!")
if len(name) > 5:
raise ValueError("⚠ 자동차 이름은 5자 이하만 가능합니다!")
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 29-29: E501 line too long (87 > 79 characters)


try:
N = int(input("시도할 횟수는 몇 회인가요? "))
if N <= 0:
raise ValueError("⚠ 시도 횟수는 1 이상이어야 합니다!")
except ValueError:
print("⚠ 잘못된 입력입니다. 숫자를 입력하세요.")
return

Check warning on line 41 in src/racingcar/main.py

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L38-L41

Added lines #L38 - L41 were not covered by tests
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

예외 처리 로직을 개선해야 합니다.

시도 횟수 입력 처리에서 다음과 같은 문제가 있습니다:

  • 예외 발생 시 단순히 반환하는 것보다 예외를 발생시키는 것이 더 적절합니다
  • 음수와 0에 대한 처리가 분리되어 있어 코드가 복잡합니다

다음과 같이 개선하는 것을 제안합니다:

     try:
         N = int(input("시도할 횟수는 몇 회인가요? "))
-        if N <= 0:
-            raise ValueError("⚠ 시도 횟수는 1 이상이어야 합니다!")
-    except ValueError:
-        print("⚠ 잘못된 입력입니다. 숫자를 입력하세요.")
-        return
+        if N < 1:
+            raise ValueError("⚠ 시도 횟수는 1 이상이어야 합니다!")
+    except ValueError as e:
+        raise ValueError("⚠ 잘못된 입력입니다. 1 이상의 숫자를 입력하세요.")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
N = int(input("시도할 횟수는 몇 회인가요? "))
if N <= 0:
raise ValueError("⚠ 시도 횟수는 1 이상이어야 합니다!")
except ValueError:
print("⚠ 잘못된 입력입니다. 숫자를 입력하세요.")
return
try:
N = int(input("시도할 횟수는 몇 회인가요? "))
if N < 1:
raise ValueError("⚠ 시도 횟수는 1 이상이어야 합니다!")
except ValueError as e:
raise ValueError("⚠ 잘못된 입력입니다. 1 이상의 숫자를 입력하세요.")


car_positions = {name: 0 for name in car_names} # 자동차 위치 초기화

for _ in range(N):
move_cars(car_positions) # 자동차 이동
print_race(car_positions) # 현재 상태 출력

winners = get_winners(car_positions) # 우승자 결정
print(f"\n최종 우승자 : {', '.join(winners)}")


if __name__ == "__main__":
# 프로그램이 직접 실행될 때만 main() 함수를 호출
main()
2 changes: 1 addition & 1 deletion tests/racingcar/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_전진_및_정지(capsys):
main() # 프로그램 실행

# 출력값을 캡처한 후 검증
캡처된_출력 = capsys.readouterr()
캡처된_출력 = capsys.readouterr().out
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ㅎㅎ 제가 실수한 부분인데 잘 체크하고 고치셨어요!

assert all(예상_출력 in 캡처된_출력 for 예상_출력 in ["pobi : -", "woni : ", "최종 우승자 : pobi"])


Expand Down
Loading