-
Notifications
You must be signed in to change notification settings - Fork 5
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
base: main
Are you sure you want to change the base?
Conversation
## Walkthrough
이 PR은 `src/racingcar/main.py`, `tests/racingcar/test_main.py`, `README.md`, 및 `docs/README.md` 파일을 수정합니다. `main.py`에서는 사용자로부터 자동차 이름과 시도 횟수를 입력받아 중복 제거와 유효성 검사를 진행하고, 난수에 따라 자동차의 위치를 업데이트하며 최종 승자를 결정하는 레이싱 로직이 구현되었습니다. `test_main.py`에서는 캡처된 출력에서 표준 출력(`stdout`)만을 사용하도록 변경되어, 테스트 시 예상 출력 문자열을 올바르게 검증합니다. `README.md`와 `docs/README.md`에서는 새로운 요구 사항과 기능 목록이 추가되었습니다.
## Changes
| 파일 | 변경 요약 |
|------------------------------|------------------------------------------------------------------------------------------------------|
| src/.../main.py | 사용자 입력 처리, 이름 중복 제거 및 유효성 검사(최대 5자 제한), 난수 기반 레이스 로직 추가 (위치 업데이트 및 승자 결정) |
| tests/.../test_main.py | 캡처 출력 수정: `capsys.readouterr()`에서 표준 출력(`.out`)만 사용하도록 변경 |
| README.md | 새로운 요구 사항 섹션 추가: 코드 구조 및 테스트에 대한 프로그래밍 제약 사항 명시 |
| docs/.../README.md | 새로운 기능 목록 섹션 추가: 자동차 이름 입력, 시도 횟수 입력, 자동차 경주 진행, 경주 상태 출력, 우승자 결정 |
## Sequence Diagram(s)
```mermaid
sequenceDiagram
participant U as 사용자
participant M as main()
participant R as random 모듈
U->>M: 자동차 이름 입력
M->>M: 이름 중복 제거 및 유효성 검증
U->>M: 시도 횟수 입력
M->>M: 시도 횟수 검증
loop 각 시도마다
M->>R: 랜덤 숫자 요청
R-->>M: 1~9 사이의 랜덤 숫자 반환
M->>M: 자동차 위치 업데이트 (숫자가 4 이상일 때)
M->>U: 현재 위치 출력
end
M->>U: 최종 승자 출력 Poem
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/racingcar/main.py (2)
22-33
: 자동차 위치 업데이트 로직을 개선해야 합니다.현재 구현에서 다음과 같은 개선이 필요합니다:
- 매직 넘버(4, 9)를 상수로 분리해야 합니다
- 자동차 위치 업데이트와 출력 로직이 분리되어야 합니다
다음과 같이 개선하는 것을 제안합니다:
+ FORWARD_THRESHOLD = 4 + MAX_RANDOM = 9 + carPos = {name: 0 for name in car_dict} for _ in range(N): for name in car_dict: - rand_num = random.randint(1, 9) - if rand_num >= 4: + rand_num = random.randint(1, MAX_RANDOM) + if rand_num >= FORWARD_THRESHOLD: carPos[name] += 1 + + print_positions(carPos) - for name in carPos: - print(f"{name} : {'-' * carPos[name] if carPos[name] > 0 else ' '}") - print() # 줄바꿈 추가 +def print_positions(positions): + for name, pos in positions.items(): + print(f"{name} : {'-' * pos if pos > 0 else ' '}") + print()
34-38
: 우승자 결정 로직을 분리해야 합니다.우승자를 결정하는 로직을 별도의 함수로 분리하여 코드의 가독성과 재사용성을 높일 수 있습니다.
다음과 같이 개선하는 것을 제안합니다:
- print() # 최종 출력과 구분을 위해 개행 추가 - maxPos = max(carPos.values()) - winners = [name for name, pos in carPos.items() if pos == maxPos] - - print(f"최종 우승자 : {', '.join(winners)}") + print() + winners = determine_winners(carPos) + print(f"최종 우승자 : {', '.join(winners)}") + +def determine_winners(positions): + max_pos = max(positions.values()) + return [name for name, pos in positions.items() if pos == max_pos]
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/racingcar/main.py
(1 hunks)tests/racingcar/test_main.py
(1 hunks)
🔇 Additional comments (2)
tests/racingcar/test_main.py (1)
22-22
: 출력 캡처 방식이 개선되었습니다.표준 출력(
stdout
)만을 캡처하도록 변경하여 테스트의 정확성이 향상되었습니다.src/racingcar/main.py (1)
2-4
: 입력 처리 방식 개선이 필요합니다.사용자 입력 처리 시 다음 사항들을 고려해야 합니다:
- 빈 입력에 대한 처리가 누락되었습니다
- 입력값이 없는 경우에 대한 예외 처리가 필요합니다
다음과 같이 개선하는 것을 제안합니다:
- car_names = input("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분): ").split(",") + user_input = input("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분): ").strip() + if not user_input: + raise ValueError("⚠ 자동차 이름을 입력해주세요!") + car_names = user_input.split(",")
src/racingcar/main.py
Outdated
try: | ||
N = int(input("시도할 횟수는 몇 회인가요? ")) | ||
if N <= 0: | ||
raise ValueError("⚠ 시도 횟수는 1 이상이어야 합니다!") | ||
except ValueError: | ||
print("⚠ 잘못된 입력입니다. 숫자를 입력하세요.") | ||
return |
There was a problem hiding this comment.
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.
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 이상의 숫자를 입력하세요.") |
Welcome to Codecov 🎉Once you merge this PR into your default branch, you're all set! Codecov will compare coverage reports and display results in all future pull requests. ℹ️ You can also turn on project coverage checks and project coverage reporting on Pull Request comment Thanks for integrating Codecov - We've got you covered ☂️ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (5)
src/racingcar/main.py (5)
1-1
: 모듈 수준의 문서화가 필요합니다.모듈의 목적과 기능을 설명하는 docstring을 추가해 주세요.
다음과 같이 모듈 docstring을 추가하는 것을 제안합니다:
import random +""" +자동차 경주 게임을 구현한 모듈입니다. +사용자로부터 자동차 이름과 시도 횟수를 입력받아 랜덤한 전진 로직으로 우승자를 결정합니다. +"""🧰 Tools
🪛 GitHub Actions: Check No Ternary Operator
[error] 1-1: Ternary operators are not allowed!
🪛 GitHub Actions: Check Indentation Depth
[warning] 1-1: Missing module docstring
3-8
: 함수 정의 전 빈 줄을 추가해 주세요.PEP 8 스타일 가이드에 따라 함수 정의 전에 2줄의 빈 줄이 필요합니다.
import random + def move_cars(car_positions):
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[warning] 3-3: E302 expected 2 blank lines, found 1
15-19
: 함수 정의 전 빈 줄을 추가해 주세요.PEP 8 스타일 가이드에 따라 함수 정의 전에 2줄의 빈 줄이 필요합니다.
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[warning] 15-15: E302 expected 2 blank lines, found 1
30-30
: 변수명을 snake_case 형식으로 수정해 주세요.변수 'N'은 Python 명명 규칙에 맞지 않습니다.
- N = int(input("시도할 횟수는 몇 회인가요? ")) + attempts = int(input("시도할 횟수는 몇 회인가요? "))🧰 Tools
🪛 GitHub Actions: Check Indentation Depth
[warning] 30-30: Variable name "N" doesn't conform to snake_case naming style
23-23
: 줄 길이가 너무 깁니다.PEP 8 스타일 가이드에 따라 한 줄은 79자를 넘지 않아야 합니다.
다음과 같이 줄을 나누는 것을 제안합니다:
- car_names = list(dict.fromkeys(name.strip() for name in car_names if name.strip())) # 중복 제거 (순서 유지) + # 중복 제거 (순서 유지) + car_names = [name.strip() for name in car_names if name.strip()] + car_names = list(dict.fromkeys(car_names))🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 23-23: E501 line too long (104 > 79 characters)
🪛 GitHub Actions: Check Indentation Depth
[warning] 23-23: Line too long (104/100)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/racingcar/main.py
(1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/racingcar/main.py
[warning] 32-35: src/racingcar/main.py#L32-L35
Added lines #L32 - L35 were not covered by tests
🪛 GitHub Actions: Check No Ternary Operator
src/racingcar/main.py
[error] 1-1: Ternary operators are not allowed!
🪛 GitHub Actions: Check PEP8 Style
src/racingcar/main.py
[warning] 3-3: E302 expected 2 blank lines, found 1
[warning] 9-9: E302 expected 2 blank lines, found 1
[warning] 15-15: E302 expected 2 blank lines, found 1
[warning] 20-20: E302 expected 2 blank lines, found 1
[error] 23-23: E501 line too long (104 > 79 characters)
[warning] 39-39: W291 trailing whitespace
[warning] 46-46: E305 expected 2 blank lines after class or function definition, found 1
🪛 GitHub Actions: Check Indentation Depth
src/racingcar/main.py
[warning] 23-23: Line too long (104/100)
[warning] 39-39: Trailing whitespace
[warning] 1-1: Missing module docstring
[warning] 30-30: Variable name "N" doesn't conform to snake_case naming style
🔇 Additional comments (1)
src/racingcar/main.py (1)
29-35
: 시도 횟수 입력에 대한 테스트 케이스가 필요합니다.시도 횟수 입력 처리에 대한 테스트 케이스가 누락되었습니다.
다음과 같은 테스트 케이스 추가를 제안합니다:
- 음수 입력 시 예외 처리
- 0 입력 시 예외 처리
- 문자열 입력 시 예외 처리
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 32-35: src/racingcar/main.py#L32-L35
Added lines #L32 - L35 were not covered by tests🪛 GitHub Actions: Check Indentation Depth
[warning] 30-30: Variable name "N" doesn't conform to snake_case naming style
src/racingcar/main.py
Outdated
def print_race(car_positions): | ||
"""현재 경주 상태 출력""" | ||
for name, pos in car_positions.items(): | ||
print(f"{name} : {'-' * pos if pos > 0 else ' '}") | ||
print() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
삼항 연산자 사용을 피해주세요.
파이프라인 검사에 따르면 삼항 연산자 사용이 허용되지 않습니다.
다음과 같이 일반적인 if-else 문을 사용하도록 수정해 주세요:
- print(f"{name} : {'-' * pos if pos > 0 else ' '}")
+ position_marker = '-' * pos if pos > 0 else ' '
+ print(f"{name} : {position_marker}")
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[warning] 9-9: E302 expected 2 blank lines, found 1
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (4)
src/racingcar/main.py (4)
5-9
: 입력값 검증이 필요합니다.
car_positions
딕셔너리가 None이거나 비어있는 경우에 대한 처리가 필요합니다.def move_cars(car_positions): """자동차 이동 로직 (랜덤 숫자가 4 이상이면 이동)""" + if not car_positions: + raise ValueError("자동차 위치 정보가 비어있습니다.") for name in car_positions: if random.randint(1, 9) >= 4: car_positions[name] += 1🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 5-5: E302 expected 2 blank lines, found 1
11-18
: 코드 중복을 제거할 수 있습니다.if-else 문을 제거하여 코드를 단순화할 수 있습니다.
def print_race(car_positions): """현재 경주 상태 출력""" for name, pos in car_positions.items(): - if pos > 0: - print(f"{name} : {'-' * pos}") - else: - print(f"{name} : {' '}") + position_marker = '-' * pos if pos > 0 else ' ' + print(f"{name} : {position_marker}") print()🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 11-11: E302 expected 2 blank lines, found 1
21-24
: 예외 처리가 필요합니다.빈 딕셔너리나 잘못된 입력에 대한 처리가 필요합니다.
def get_winners(car_positions): """최종 우승자 결정""" + if not car_positions: + raise ValueError("자동차 위치 정보가 비어있습니다.") max_pos = max(car_positions.values()) return [name for name, pos in car_positions.items() if pos == max_pos]
43-50
: 사용자 피드백을 개선할 수 있습니다.게임 진행 상황에 대한 추가 정보를 제공하면 좋을 것 같습니다.
car_positions = {name: 0 for name in car_names} # 자동차 위치 초기화 + print("\n실행 결과") for _ in range(N): move_cars(car_positions) # 자동차 이동 print_race(car_positions) # 현재 상태 출력 winners = get_winners(car_positions) # 우승자 결정 + print("\n경주 종료!") print(f"\n최종 우승자 : {', '.join(winners)}")🧰 Tools
🪛 GitHub Actions: Check Indentation Depth
[warning] 45-45: Trailing whitespace (trailing-whitespace)
🪛 GitHub Actions: Check PEP8 Style
[warning] 45-45: W291 trailing whitespace
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
README.md
(1 hunks)src/racingcar/main.py
(1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Check Indentation Depth
src/racingcar/main.py
[warning] 45-45: Trailing whitespace (trailing-whitespace)
[warning] 36-36: Variable name "N" doesn't conform to snake_case naming style (invalid-name)
🪛 GitHub Actions: Check PEP8 Style
src/racingcar/main.py
[error] 5-5: E302 expected 2 blank lines, found 1
[error] 11-11: E302 expected 2 blank lines, found 1
[error] 26-26: E302 expected 2 blank lines, found 1
[error] 29-29: E501 line too long (87 > 79 characters)
[warning] 45-45: W291 trailing whitespace
🔇 Additional comments (2)
src/racingcar/main.py (1)
35-41
: 예외 처리 로직을 개선해야 합니다.🧰 Tools
🪛 GitHub Actions: Check Indentation Depth
[warning] 36-36: Variable name "N" doesn't conform to snake_case naming style (invalid-name)
README.md (1)
213-234
: 구현할 기능 목록이 잘 정리되어 있습니다.기능 요구사항과 구현 내용이 잘 매칭되어 있으며, 각 기능의 세부 사항이 명확하게 기술되어 있습니다.
|
||
import random | ||
|
||
def move_cars(car_positions): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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
src/racingcar/main.py
Outdated
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자 이하만 가능합니다!") |
There was a problem hiding this comment.
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.
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)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/racingcar/main.py (3)
6-11
: 불변성을 고려한 구현을 추천드립니다.현재 구현은 입력 딕셔너리를 직접 수정하고 있습니다. 함수형 프로그래밍 원칙에 따라 새로운 딕셔너리를 반환하는 것이 더 좋습니다.
다음과 같이 수정하는 것을 제안합니다:
def move_cars(car_positions): """자동차 이동 로직 (랜덤 숫자가 4 이상이면 이동)""" - + new_positions = car_positions.copy() for name in car_positions: if random.randint(1, 9) >= 4: - car_positions[name] += 1 + new_positions[name] += 1 + return new_positions
14-22
: 출력 로직을 단순화할 수 있습니다.현재 if-else 구문을 삼항 연산자로 단순화할 수 있지만, 파이프라인 검사에서 삼항 연산자 사용이 허용되지 않으므로 다른 방식으로 개선하겠습니다.
다음과 같이 수정하는 것을 제안합니다:
def print_race(car_positions): """현재 경주 상태 출력""" for name, pos in car_positions.items(): - if pos > 0: - print(f"{name} : {'-' * pos}") - else: - print(f"{name} : {' '}") # Trailing whitespace 제거 + position_marker = '-' * pos if pos > 0 else ' ' + print(f"{name} : {position_marker}") print()
50-57
: 게임 로직을 별도의 함수로 분리하는 것이 좋습니다.현재 main 함수가 너무 많은 책임을 가지고 있습니다.
다음과 같이 게임 로직을 분리하는 것을 제안합니다:
+def run_game(car_positions, attempts): + """게임 실행 로직""" + for _ in range(attempts): + car_positions = move_cars(car_positions) + print_race(car_positions) + return car_positions + def main(): # ... 입력 처리 코드 ... car_positions = {name: 0 for name in car_names} - for _ in range(N): - move_cars(car_positions) - print_race(car_positions) + car_positions = run_game(car_positions, N) winners = get_winners(car_positions) print(f"\n최종 우승자 : {', '.join(winners)}")🧰 Tools
🪛 GitHub Actions: Check Indentation Depth
[warning] 52-52: Trailing whitespace (trailing-whitespace)
🪛 GitHub Actions: Check PEP8 Style
[warning] 52-52: trailing whitespace
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/racingcar/main.py
(1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Check Indentation Depth
src/racingcar/main.py
[warning] 52-52: Trailing whitespace (trailing-whitespace)
[warning] 43-43: Variable name "N" doesn't conform to snake_case naming style (invalid-name)
🪛 GitHub Actions: Check PEP8 Style
src/racingcar/main.py
[error] 36-36: line too long (87 > 79 characters)
[warning] 52-52: trailing whitespace
[warning] 59-59: expected 2 blank lines after class or function definition, found 1
🔇 Additional comments (4)
src/racingcar/main.py (4)
1-4
: 모듈 수준 코드가 깔끔합니다!모듈 문서화와 필요한 import만 포함되어 있어 좋습니다.
25-29
: 우승자 결정 로직이 잘 구현되었습니다!최대값을 찾고 해당하는 모든 우승자를 리스트로 반환하는 로직이 깔끔합니다.
35-40
: 입력값 검증을 강화해야 합니다.자동차 이름에 대한 추가 검증이 필요합니다.
다음과 같이 수정하는 것을 제안합니다:
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] 36-36: line too long (87 > 79 characters)
42-48
: 예외 처리 로직을 개선해야 합니다.시도 횟수 입력 처리에서 예외 처리가 일관되지 않습니다.
다음과 같이 수정하는 것을 제안합니다:
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 이상의 숫자를 입력하세요.")🧰 Tools
🪛 GitHub Actions: Check Indentation Depth
[warning] 43-43: Variable name "N" doesn't conform to snake_case naming style (invalid-name)
src/racingcar/main.py
Outdated
"""메인 함수""" | ||
|
||
car_names = input("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분): ").split(",") | ||
car_names = list(dict.fromkeys(name.strip() for name in car_names if name.strip())) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
PEP8 스타일 가이드를 준수해야 합니다.
파이프라인 검사에서 발견된 스타일 문제를 수정해야 합니다.
다음 사항들을 수정해 주세요:
- 36번 줄이 최대 길이(79자)를 초과합니다
- 43번 줄의 변수
N
은 snake_case 명명 규칙을 따라야 합니다 - 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)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/racingcar/main.py (1)
14-22
: print_race 함수를 더 간단하게 개선할 수 있습니다.
rstrip()
은 빈 문자열을 출력할 때 불필요합니다.다음과 같이 수정하는 것을 제안합니다:
def print_race(car_positions): """현재 경주 상태 출력""" for name, pos in car_positions.items(): if pos > 0: print(f"{name} : {'-' * pos}") else: - print(f"{name} : {' '.rstrip()}") # Trailing whitespace 제거 + print(f"{name} : ") print()
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
README.md
(1 hunks)docs/README.md
(1 hunks)src/racingcar/main.py
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- README.md
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/racingcar/main.py
[warning] 47-50: src/racingcar/main.py#L47-L50
Added lines #L47 - L50 were not covered by tests
🪛 GitHub Actions: Check PEP8 Style
src/racingcar/main.py
[error] 36-36: Continuation line under-indented for visual indent.
[error] 38-38: Continuation line under-indented for visual indent.
🔇 Additional comments (4)
src/racingcar/main.py (3)
6-11
: 구현이 깔끔하고 요구사항에 잘 부합합니다!함수가 간단하고 목적에 맞게 잘 구현되어 있습니다.
25-29
: 우승자 결정 로직이 잘 구현되어 있습니다!리스트 컴프리헨션을 효과적으로 활용하여 간결하게 구현되었습니다.
44-50
: 예외 처리에 대한 테스트 케이스가 필요합니다.시도 횟수 입력에 대한 예외 처리 코드가 테스트되지 않았습니다.
테스트 케이스를 추가하여 다음 시나리오들을 검증해주세요:
- 음수 입력 시 예외 발생
- 0 입력 시 예외 발생
- 문자열 입력 시 예외 발생
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 47-50: src/racingcar/main.py#L47-L50
Added lines #L47 - L50 were not covered by testsdocs/README.md (1)
1-22
: 문서가 명확하고 체계적으로 작성되었습니다!구현할 기능이 상세하게 정리되어 있고, 실제 구현과도 잘 일치합니다.
src/racingcar/main.py
Outdated
car_names = input("경주할 자동차 이름을 입력하세요." | ||
"(이름은 쉼표로 구분): ").split(",") | ||
car_names = list(dict.fromkeys(name.strip() for name in car_names | ||
if name.strip())) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
들여쓰기를 PEP8 스타일 가이드에 맞게 수정해야 합니다.
파이프라인 검사에서 발견된 들여쓰기 문제를 수정해야 합니다.
다음과 같이 수정하는 것을 제안합니다:
- car_names = input("경주할 자동차 이름을 입력하세요."
- "(이름은 쉼표로 구분): ").split(",")
- car_names = list(dict.fromkeys(name.strip() for name in car_names
- if name.strip()))
+ car_names = input("경주할 자동차 이름을 입력하세요."
+ "(이름은 쉼표로 구분): ").split(",")
+ car_names = list(dict.fromkeys(name.strip() for name in car_names
+ if name.strip()))
📝 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.
car_names = input("경주할 자동차 이름을 입력하세요." | |
"(이름은 쉼표로 구분): ").split(",") | |
car_names = list(dict.fromkeys(name.strip() for name in car_names | |
if name.strip())) | |
car_names = input("경주할 자동차 이름을 입력하세요." | |
"(이름은 쉼표로 구분): ").split(",") | |
car_names = list(dict.fromkeys(name.strip() for name in car_names | |
if name.strip())) |
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 36-36: Continuation line under-indented for visual indent.
[error] 38-38: Continuation line under-indented for visual indent.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/racingcar/main.py (1)
14-22
: print_race 함수의 가독성을 개선할 수 있습니다.21번 줄의
rstrip()
호출이 불필요합니다. 빈 문자열은 이미 공백이 없는 상태입니다.다음과 같이 수정하는 것을 제안합니다:
- print(f"{name} : {' '.rstrip()}") # Trailing whitespace 제거 + print(f"{name} : ") # 진행하지 않은 경우 빈 공간 출력
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/racingcar/main.py
(1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/racingcar/main.py
[warning] 47-50: src/racingcar/main.py#L47-L50
Added lines #L47 - L50 were not covered by tests
🪛 GitHub Actions: Check PEP8 Style
src/racingcar/main.py
[error] 38-38: Continuation line over-indented for visual indent.
🔇 Additional comments (4)
src/racingcar/main.py (4)
1-4
: 코드 구조가 깔끔합니다!파일 상단의 문서화와 import 구문이 잘 정리되어 있습니다.
44-50
: 예외 처리에 대한 테스트 케이스가 필요합니다.시도 횟수 입력에 대한 예외 처리 로직이 테스트되지 않았습니다. 다음과 같은 테스트 케이스를 추가해야 합니다:
- 음수 입력
- 0 입력
- 문자열 입력
테스트 케이스 작성을 도와드릴까요?
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 47-50: src/racingcar/main.py#L47-L50
Added lines #L47 - L50 were not covered by tests
35-38
: 들여쓰기를 PEP8 스타일 가이드에 맞게 수정해야 합니다.파이프라인 검사에서 발견된 들여쓰기 문제를 수정해야 합니다.
다음과 같이 수정하는 것을 제안합니다:
- car_names = input("경주할 자동차 이름을 입력하세요." - "(이름은 쉼표로 구분): ").split(",") - car_names = list(dict.fromkeys(name.strip() for name in car_names - if name.strip())) # 들여쓰기 수정 + car_names = input("경주할 자동차 이름을 입력하세요." + "(이름은 쉼표로 구분): ").split(",") + car_names = list(dict.fromkeys( + name.strip() for name in car_names if name.strip() + ))🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 38-38: Continuation line over-indented for visual indent.
62-63
: 메인 실행 블록이 적절합니다!Python의 표준적인 진입점 패턴을 잘 따르고 있습니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/racingcar/main.py (3)
6-11
: 타입 힌트를 추가하여 코드의 가독성을 개선하세요.타입 힌트를 추가하면 코드의 의도가 더 명확해지고 유지보수가 쉬워집니다.
다음과 같이 수정하는 것을 제안합니다:
-def move_cars(car_positions): +def move_cars(car_positions: dict[str, int]) -> None:
14-22
: 타입 힌트 추가 및 주석 개선이 필요합니다.
- 타입 힌트를 추가하여 함수의 입력과 출력 타입을 명확히 해주세요.
- 영문 주석은 한글로 작성하는 것이 좋습니다.
다음과 같이 수정하는 것을 제안합니다:
-def print_race(car_positions): +def print_race(car_positions: dict[str, int]) -> None: """현재 경주 상태 출력""" for name, pos in car_positions.items(): if pos > 0: print(f"{name} : {'-' * pos}") else: - print(f"{name} : {' '.rstrip()}") # Trailing whitespace 제거 + print(f"{name} : {' '.rstrip()}") # 끝부분 공백 제거
25-29
: 타입 힌트를 추가하여 함수의 입출력을 명확히 하세요.반환값이 문자열 리스트라는 것을 명시하면 함수의 사용이 더 명확해집니다.
다음과 같이 수정하는 것을 제안합니다:
-def get_winners(car_positions): +def get_winners(car_positions: dict[str, int]) -> list[str]:
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/racingcar/main.py
(1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/racingcar/main.py
[warning] 48-51: src/racingcar/main.py#L48-L51
Added lines #L48 - L51 were not covered by tests
🔇 Additional comments (2)
src/racingcar/main.py (2)
45-51
: 예외 처리에 대한 테스트 케이스가 누락되었습니다.시도 횟수 입력에 대한 예외 처리 로직이 테스트되지 않았습니다. 다음과 같은 테스트 케이스를 추가해주세요:
- 음수 입력 시 예외 처리
- 0 입력 시 예외 처리
- 문자열 입력 시 예외 처리
테스트 케이스 작성을 도와드릴까요?
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 48-51: src/racingcar/main.py#L48-L51
Added lines #L48 - L51 were not covered by tests
1-4
: 모듈 레벨 구성이 잘 되어있습니다!모듈 독스트링, import 문, main 가드가 적절히 구성되어 있습니다.
Also applies to: 63-64
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자 이하만 가능합니다!") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
입력 검증 로직을 별도 함수로 분리하세요.
현재 main 함수가 너무 많은 책임을 가지고 있습니다. 입력 검증 로직을 분리하면 코드의 가독성과 재사용성이 향상됩니다.
다음과 같이 분리하는 것을 제안합니다:
+def validate_car_names(names: list[str]) -> None:
+ """자동차 이름 유효성 검사"""
+ if not names:
+ raise ValueError("⚠ 유효한 자동차 이름이 없습니다!")
+ for name in names:
+ if len(name) > 5:
+ raise ValueError("⚠ 자동차 이름은 5자 이하만 가능합니다!")
def main():
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자 이하만 가능합니다!")
+ validate_car_names(car_names)
📝 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.
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자 이하만 가능합니다!") | |
def validate_car_names(names: list[str]) -> None: | |
"""자동차 이름 유효성 검사""" | |
if not names: | |
raise ValueError("⚠ 유효한 자동차 이름이 없습니다!") | |
for name in names: | |
if len(name) > 5: | |
raise ValueError("⚠ 자동차 이름은 5자 이하만 가능합니다!") | |
def main(): | |
car_names = input("경주할 자동차 이름을 입력하세요." | |
"(이름은 쉼표로 구분): ").split(",") | |
car_names = list(dict.fromkeys( | |
name.strip() for name in car_names if name.strip() | |
)) | |
validate_car_names(car_names) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
전반적으로 잘 하셨습니다.
어째서 git commit convention은 안 지키시는거죠 😭
다음 과제부턴 주의해주세요 (제대로 안하면 담 과제부턴 자동화에서 걸려요ㅎ)
racingcar 관련해서는 요구사항에 맞춰 개선해주세요~
"""자동차 이동 로직 (랜덤 숫자가 4 이상이면 이동)""" | ||
|
||
for name in car_positions: | ||
if random.randint(1, 9) >= 4: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
숫자상수는, 매직넘버상수로 바꾸고 전방선언 해주는 것이 좋습니다.
def print_race(car_positions): | ||
"""현재 경주 상태 출력""" | ||
|
||
for name, pos in car_positions.items(): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pos도 좋지만 position
처럼 풀네임으로 작성하는 것도 고민해보세요.
)) # ✅ 올바른 들여쓰기 수정 | ||
|
||
for name in car_names: | ||
if len(name) > 5: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
숫자상수는, 매직넘버상수로 바꾸고 전방선언 해주는 것이 좋습니다.
@@ -19,7 +19,7 @@ def test_전진_및_정지(capsys): | |||
main() # 프로그램 실행 | |||
|
|||
# 출력값을 캡처한 후 검증 | |||
캡처된_출력 = capsys.readouterr() | |||
캡처된_출력 = capsys.readouterr().out |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ㅎㅎ 제가 실수한 부분인데 잘 체크하고 고치셨어요!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/racingcar/main.py
(1 hunks)tests/study/test_string.py
(1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/racingcar/main.py
1-1: SyntaxError: Expected a statement
1-1: SyntaxError: Expected a statement
1-1: SyntaxError: Expected a statement
1-1: SyntaxError: Expected a statement
3-3: SyntaxError: Expected a statement
3-3: SyntaxError: Expected a statement
3-3: SyntaxError: Expected a statement
3-3: SyntaxError: Expected a statement
3-4: SyntaxError: Expected a statement
5-5: SyntaxError: Expected a statement
5-5: SyntaxError: Expected a statement
5-5: SyntaxError: Expected a statement
5-5: SyntaxError: Expected a statement
10-10: SyntaxError: Expected a statement
10-10: SyntaxError: Expected a statement
10-10: SyntaxError: Expected a statement
10-10: SyntaxError: Expected a statement
22-23: SyntaxError: Expected an indented block after if
statement
23-23: SyntaxError: Expected a statement
23-23: SyntaxError: Expected a statement
23-23: SyntaxError: Expected a statement
23-23: SyntaxError: Expected a statement
23-24: SyntaxError: Expected a statement
28-29: SyntaxError: Expected an indented block after if
statement
29-29: SyntaxError: Expected a statement
29-29: SyntaxError: Expected a statement
29-29: SyntaxError: Expected a statement
29-29: SyntaxError: Expected a statement
30-30: SyntaxError: Unexpected indentation
33-33: SyntaxError: Expected a statement
48-48: SyntaxError: Expected a statement
48-48: SyntaxError: Expected a statement
48-48: SyntaxError: Expected a statement
48-48: SyntaxError: Expected a statement
49-49: SyntaxError: Unexpected indentation
52-52: SyntaxError: Expected a statement
52-52: SyntaxError: Expected a statement
52-52: SyntaxError: Expected a statement
52-52: SyntaxError: Expected a statement
52-53: SyntaxError: Expected a statement
53-53: SyntaxError: Unexpected indentation
54-54: SyntaxError: Expected a statement
54-54: SyntaxError: Expected a statement
54-54: SyntaxError: Expected a statement
54-54: SyntaxError: Expected a statement
60-60: SyntaxError: Expected a statement
60-60: SyntaxError: Expected a statement
60-60: SyntaxError: Expected a statement
60-60: SyntaxError: Expected a statement
61-61: SyntaxError: Unexpected indentation
77-77: SyntaxError: Expected except
or finally
after try
block
77-77: SyntaxError: Expected a statement
77-77: SyntaxError: Expected a statement
77-77: SyntaxError: Expected a statement
77-78: SyntaxError: Expected a statement
78-78: SyntaxError: Unexpected indentation
90-90: SyntaxError: Expected except
or finally
after try
block
90-90: SyntaxError: Expected a statement
90-90: SyntaxError: Expected a statement
90-90: SyntaxError: Expected a statement
91-91: SyntaxError: Unexpected indentation
93-93: SyntaxError: unindent does not match any outer indentation level
93-94: SyntaxError: Expected an expression
94-94: SyntaxError: Unexpected indentation
97-97: SyntaxError: unindent does not match any outer indentation level
99-99: SyntaxError: Expected a statement
99-99: SyntaxError: Expected a statement
99-99: SyntaxError: Expected a statement
99-99: SyntaxError: Expected a statement
100-100: SyntaxError: Unexpected indentation
100-101: SyntaxError: Expected an indented block after for
statement
101-101: SyntaxError: Expected a statement
101-101: SyntaxError: Expected a statement
101-101: SyntaxError: Expected a statement
101-101: SyntaxError: Expected a statement
101-102: SyntaxError: Expected a statement
102-102: SyntaxError: Unexpected indentation
102-103: SyntaxError: Expected an indented block after for
statement
103-103: SyntaxError: Expected a statement
103-103: SyntaxError: Expected a statement
103-103: SyntaxError: Expected a statement
103-103: SyntaxError: Expected a statement
104-104: SyntaxError: Unexpected indentation
107-107: SyntaxError: unindent does not match any outer indentation level
108-108: SyntaxError: Unexpected indentation
111-111: SyntaxError: Expected a statement
🪛 GitHub Actions: Check Indentation Depth
src/racingcar/main.py
[error] 1-1: Parsing failed: 'invalid syntax (racingcar.main, line 1)'
🪛 GitHub Actions: Check No External Libraries
src/racingcar/main.py
[error] 1-1: SyntaxError: invalid syntax due to merge conflict markers (<<<<<<< HEAD).
🪛 GitHub Actions: Run tests and upload coverage
src/racingcar/main.py
[error] 1-1: SyntaxError: invalid syntax due to unresolved merge conflict markers.
🪛 GitHub Actions: Check PEP8 Style
src/racingcar/main.py
[error] 1-1: SyntaxError: invalid syntax
🔇 Additional comments (1)
tests/study/test_string.py (1)
63-63
: LGTM! 미사용 변수 처리가 개선되었습니다.
_
를 사용하여 미사용 변수를 명시적으로 표시한 것은 좋은 방법입니다.
if num_attempts <= 0: | ||
raise ValueError("⚠ 시도 횟수는 1 이상이어야 합니다!") | ||
except ValueError: | ||
print("⚠ 잘못된 입력입니다. 숫자를 입력하세요.") | ||
return | ||
|
||
car_positions = {name: 0 for name in car_names} # 자동차 위치 초기화 | ||
|
||
<<<<<<< HEAD | ||
for _ in range(num_attempts): | ||
======= | ||
for _ in range(num_attempts): # 변수명 수정 | ||
>>>>>>> a8f68ff7178f271a24793fe592b609c29719c4aa | ||
move_cars(car_positions) # 자동차 이동 | ||
print_race(car_positions) # 현재 상태 출력 | ||
|
||
winners = get_winners(car_positions) # 우승자 결정 | ||
print(f"\n최종 우승자 : {', '.join(winners)}") | ||
|
||
|
||
if __name__ == "__main__": | ||
main() # ✅ 마지막 빈 줄 제거 (W391 해결) 현재 코드에서 """자동차 경주 게임 메인 스크립트""" | ||
|
||
import random | ||
|
||
|
||
# 상수 정의 | ||
MOVE_THRESHOLD = 4 # 자동차가 전진할 최소 랜덤 값 | ||
MIN_RAND = 1 # 랜덤 숫자의 최소값 | ||
MAX_RAND = 9 # 랜덤 숫자의 최대값 | ||
MAX_NAME_LENGTH = 5 # 자동차 이름 최대 길이 | ||
|
||
|
||
def move_cars(car_positions): | ||
"""자동차 이동 로직 (랜덤 숫자가 MOVE_THRESHOLD 이상이면 이동)""" | ||
|
||
for name in car_positions: | ||
if random.randint(MIN_RAND, MAX_RAND) >= MOVE_THRESHOLD: | ||
car_positions[name] += 1 | ||
|
||
|
||
def print_race(car_positions): | ||
"""현재 경주 상태 출력""" | ||
|
||
for name, pos in car_positions.items(): | ||
if pos > 0: | ||
print(f"{name} : {'-' * pos}") | ||
else: | ||
print(f"{name} : {' '.rstrip()}") # Trailing whitespace 제거 | ||
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(): | ||
"""메인 함수""" | ||
|
||
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) > MAX_NAME_LENGTH: | ||
raise ValueError( | ||
f"⚠ 자동차 이름은 {MAX_NAME_LENGTH}자 이하만 가능합니다!" | ||
) # ✅ 긴 문자열 개행 처리 | ||
|
||
try: | ||
num_attempts = int(input("시도할 횟수는 몇 회인가요? ")) # 시도 횟수 입력 | ||
if num_attempts <= 0: | ||
raise ValueError("⚠ 시도 횟수는 1 이상이어야 합니다!") | ||
except ValueError: | ||
print("⚠ 잘못된 입력입니다. 숫자를 입력하세요.") | ||
return | ||
|
||
car_positions = {name: 0 for name in car_names} # 자동차 위치 초기화 | ||
|
||
for _ in range(num_attempts): | ||
move_cars(car_positions) # 자동차 이동 | ||
print_race(car_positions) # 현재 상태 출력 | ||
|
||
winners = get_winners(car_positions) # 우승자 결정 | ||
print(f"\n최종 우승자 : {', '.join(winners)}") | ||
|
||
|
||
if __name__ == "__main__": | ||
# 프로그램이 직접 실행될 때만 main() 함수를 호출 | ||
main() | ||
main() # ✅ 마지막 빈 줄 제거 (W391 해결) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🚨 병합 충돌을 해결해야 합니다.
파일에 해결되지 않은 병합 충돌이 있습니다:
<<<<<<< HEAD
,=======
,>>>>>>> a8f68ff7178f271a24793fe592b609c29719c4aa
마커가 여러 곳에 남아있습니다.- 이로 인해 파이프라인 검사가 실패하고 있습니다.
병합 충돌을 해결하고 다시 커밋해주세요. 병합 시에는 다음 사항을 고려해주세요:
- 상수 정의 부분은 HEAD 버전을 선택하는 것이 좋습니다 (매직 넘버 제거).
- 들여쓰기는 PEP8 스타일을 따르도록 해주세요.
- 중복된 코드 블록을 제거해주세요 (114-188줄이 1-113줄과 중복됨).
🧰 Tools
🪛 Ruff (0.8.2)
1-1: SyntaxError: Expected a statement
1-1: SyntaxError: Expected a statement
1-1: SyntaxError: Expected a statement
1-1: SyntaxError: Expected a statement
3-3: SyntaxError: Expected a statement
3-3: SyntaxError: Expected a statement
3-3: SyntaxError: Expected a statement
3-3: SyntaxError: Expected a statement
3-4: SyntaxError: Expected a statement
5-5: SyntaxError: Expected a statement
5-5: SyntaxError: Expected a statement
5-5: SyntaxError: Expected a statement
5-5: SyntaxError: Expected a statement
10-10: SyntaxError: Expected a statement
10-10: SyntaxError: Expected a statement
10-10: SyntaxError: Expected a statement
10-10: SyntaxError: Expected a statement
22-23: SyntaxError: Expected an indented block after if
statement
23-23: SyntaxError: Expected a statement
23-23: SyntaxError: Expected a statement
23-23: SyntaxError: Expected a statement
23-23: SyntaxError: Expected a statement
23-24: SyntaxError: Expected a statement
28-29: SyntaxError: Expected an indented block after if
statement
29-29: SyntaxError: Expected a statement
29-29: SyntaxError: Expected a statement
29-29: SyntaxError: Expected a statement
29-29: SyntaxError: Expected a statement
30-30: SyntaxError: Unexpected indentation
33-33: SyntaxError: Expected a statement
48-48: SyntaxError: Expected a statement
48-48: SyntaxError: Expected a statement
48-48: SyntaxError: Expected a statement
48-48: SyntaxError: Expected a statement
49-49: SyntaxError: Unexpected indentation
52-52: SyntaxError: Expected a statement
52-52: SyntaxError: Expected a statement
52-52: SyntaxError: Expected a statement
52-52: SyntaxError: Expected a statement
52-53: SyntaxError: Expected a statement
53-53: SyntaxError: Unexpected indentation
54-54: SyntaxError: Expected a statement
54-54: SyntaxError: Expected a statement
54-54: SyntaxError: Expected a statement
54-54: SyntaxError: Expected a statement
60-60: SyntaxError: Expected a statement
60-60: SyntaxError: Expected a statement
60-60: SyntaxError: Expected a statement
60-60: SyntaxError: Expected a statement
61-61: SyntaxError: Unexpected indentation
77-77: SyntaxError: Expected except
or finally
after try
block
77-77: SyntaxError: Expected a statement
77-77: SyntaxError: Expected a statement
77-77: SyntaxError: Expected a statement
77-78: SyntaxError: Expected a statement
78-78: SyntaxError: Unexpected indentation
90-90: SyntaxError: Expected except
or finally
after try
block
90-90: SyntaxError: Expected a statement
90-90: SyntaxError: Expected a statement
90-90: SyntaxError: Expected a statement
91-91: SyntaxError: Unexpected indentation
93-93: SyntaxError: unindent does not match any outer indentation level
93-94: SyntaxError: Expected an expression
94-94: SyntaxError: Unexpected indentation
97-97: SyntaxError: unindent does not match any outer indentation level
99-99: SyntaxError: Expected a statement
99-99: SyntaxError: Expected a statement
99-99: SyntaxError: Expected a statement
99-99: SyntaxError: Expected a statement
100-100: SyntaxError: Unexpected indentation
100-101: SyntaxError: Expected an indented block after for
statement
101-101: SyntaxError: Expected a statement
101-101: SyntaxError: Expected a statement
101-101: SyntaxError: Expected a statement
101-101: SyntaxError: Expected a statement
101-102: SyntaxError: Expected a statement
102-102: SyntaxError: Unexpected indentation
102-103: SyntaxError: Expected an indented block after for
statement
103-103: SyntaxError: Expected a statement
103-103: SyntaxError: Expected a statement
103-103: SyntaxError: Expected a statement
103-103: SyntaxError: Expected a statement
104-104: SyntaxError: Unexpected indentation
107-107: SyntaxError: unindent does not match any outer indentation level
108-108: SyntaxError: Unexpected indentation
111-111: SyntaxError: Expected a statement
🪛 GitHub Actions: Check Indentation Depth
[error] 1-1: Parsing failed: 'invalid syntax (racingcar.main, line 1)'
🪛 GitHub Actions: Check No External Libraries
[error] 1-1: SyntaxError: invalid syntax due to merge conflict markers (<<<<<<< HEAD).
🪛 GitHub Actions: Run tests and upload coverage
[error] 1-1: SyntaxError: invalid syntax due to unresolved merge conflict markers.
🪛 GitHub Actions: Check PEP8 Style
[error] 1-1: SyntaxError: invalid syntax
Summary by CodeRabbit