-
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
[자동차 경주] 원영진 과제 제출합니다. #5
base: main
Are you sure you want to change the base?
Conversation
racingcar 최초 모델 생성성
""" Walkthrough이번 변경으로 Changes
Sequence Diagram(s)sequenceDiagram
participant U as 사용자
participant M as Main
participant V as 검증 함수 (is_number, validate_input, try_input)
participant G as 게임 로직 (play_1set_of_game, check_winner)
U->>M: 자동차 이름 및 시도 횟수 입력
M->>V: is_number(), validate_input(), try_input() 호출
V-->>M: 입력 검증 결과 반환
M->>G: play_1set_of_game() 호출 (각 라운드 시뮬레이션)
G-->>M: 라운드 결과 반환
M->>G: check_winner() 호출 (최종 승자 판정)
G-->>M: 승자 정보 반환
M->>U: 최종 결과 출력
Poem
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Codecov ReportAttention: Patch coverage is
|
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
🔭 Outside diff range comments (1)
src/racingcar/main.py (1)
1-72
: 전체 파일의 스타일 개선이 필요합니다.
- PEP8 스타일 가이드를 준수하지 않는 여러 문제가 있습니다:
- 함수 사이 빈 줄이 부족합니다
- 불필요한 공백이 있습니다
- 함수 이름과 괄호 사이 공백이 있습니다
- 파일 끝의 빈 줄이 너무 많습니다
파일 전체에 걸쳐 PEP8 스타일 가이드를 준수하도록 수정해주세요.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 10-11: src/racingcar/main.py#L10-L11
Added lines #L10 - L11 were not covered by tests
[warning] 39-39: src/racingcar/main.py#L39
Added line #L39 was not covered by tests🪛 GitHub Actions: Check Indentation Depth
[warning] 62-62: Trailing whitespace
[warning] 65-65: Trailing whitespace
🪛 GitHub Actions: Check PEP8 Style
[error] 3-3: E302 expected 2 blank lines, found 1
[error] 3-3: E211 whitespace before '('
[error] 13-13: E302 expected 2 blank lines, found 1
[error] 20-20: E302 expected 2 blank lines, found 1
[error] 26-26: E302 expected 2 blank lines, found 1
[error] 33-33: E302 expected 2 blank lines, found 1
[warning] 62-62: W293 blank line contains whitespace
[warning] 65-65: W293 blank line contains whitespace
[error] 69-69: E303 too many blank lines (5)
🧹 Nitpick comments (4)
src/racingcar/main.py (4)
13-18
: 입력 검증 함수의 개선이 필요합니다.
- 함수가 입력 리스트를 직접 수정하는 것은 예상치 못한 부작용을 일으킬 수 있습니다
- 변수명이 더 명확할 수 있습니다
아래와 같이 수정을 제안합니다:
-def validate_input(Data): +def validate_input(car_names): + """자동차 이름 목록을 검증하고 초기 점수와 함께 반환합니다.""" + validated_cars = [] - for i in range(len(Data)): - if len(Data[i]) > 5: + for name in car_names: + if len(name) > 5: raise ValueError("이름은 5자 이하만 가능합니다.") - Data[i] = [Data[i], 0] - return Data + validated_cars.append([name, 0]) + return validated_cars🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 13-13: E302 expected 2 blank lines, found 1
20-24
: 시도 횟수 입력 함수의 개선이 필요합니다.
- 음수나 0 입력에 대한 검증이 없습니다
- 함수 설명을 위한 docstring이 누락되었습니다
아래와 같이 수정을 제안합니다:
def try_input(): + """ + 사용자로부터 시도 횟수를 입력받고 검증합니다. + Returns: + int: 유효한 시도 횟수 + Raises: + ValueError: 입력이 유효하지 않은 경우 + """ print("시도할 횟수는 몇 회인가요?") n = input() is_number(n) - return int(n) + attempts = int(n) + if attempts <= 0: + raise ValueError("시도 횟수는 1 이상이어야 합니다.") + return attempts🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 20-20: E302 expected 2 blank lines, found 1
26-31
: 게임 라운드 실행 함수의 개선이 필요합니다.
- 매직 넘버(4)를 상수로 분리해야 합니다
- 함수명이 Python 스타일 가이드를 따르지 않습니다
아래와 같이 수정을 제안합니다:
+FORWARD_THRESHOLD = 4 # 전진 기준값 + -def play_1set_of_game(Data): +def play_game_round(cars): + """한 라운드의 게임을 진행합니다.""" - for i in range(len(Data)): - value = random.randint(0, 10) - if value >= 4: - Data[i][1] += 1 - return Data + for car in cars: + if random.randint(0, 9) >= FORWARD_THRESHOLD: + car[1] += 1 + return cars🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 26-26: E302 expected 2 blank lines, found 1
33-40
: 우승자 확인 함수의 개선이 필요합니다.
- 변수명이 더 명확할 수 있습니다
- 타입 힌트 추가가 필요합니다
- 테스트 커버리지가 부족합니다
아래와 같이 수정을 제안합니다:
-def check_winner(Data): +def check_winner(cars: list[list[str, int]]) -> list[str]: + """ + 최고 점수를 가진 우승자들을 반환합니다. + + Args: + cars: [이름, 점수]를 요소로 가지는 리스트 + Returns: + 우승자 이름 리스트 + """ - win_list, winner_count = list(), 0 + winners = [] + max_score = 0 - for i in range(len(Data)): - if Data[i][1] > winner_count: - win_list, winner_count = [Data[i][0]], Data[i][1] - elif Data[i][1] == winner_count: - win_list.append(Data[i][0]) - return win_list + for name, score in cars: + if score > max_score: + winners = [name] + max_score = score + elif score == max_score: + winners.append(name) + return winners테스트 케이스를 추가하여 코드 커버리지를 개선해주세요.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 39-39: src/racingcar/main.py#L39
Added line #L39 was not covered by tests🪛 GitHub Actions: Check PEP8 Style
[error] 33-33: E302 expected 2 blank lines, found 1
📜 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] 10-11: src/racingcar/main.py#L10-L11
Added lines #L10 - L11 were not covered by tests
[warning] 39-39: src/racingcar/main.py#L39
Added line #L39 was not covered by tests
🪛 GitHub Actions: Check Indentation Depth
src/racingcar/main.py
[warning] 62-62: Trailing whitespace
[warning] 65-65: Trailing whitespace
🪛 GitHub Actions: Check PEP8 Style
src/racingcar/main.py
[error] 3-3: E302 expected 2 blank lines, found 1
[error] 3-3: E211 whitespace before '('
[error] 13-13: E302 expected 2 blank lines, found 1
[error] 20-20: E302 expected 2 blank lines, found 1
[error] 26-26: E302 expected 2 blank lines, found 1
[error] 33-33: E302 expected 2 blank lines, found 1
[warning] 62-62: W293 blank line contains whitespace
[warning] 65-65: W293 blank line contains whitespace
[error] 69-69: E303 too many blank lines (5)
src/racingcar/main.py
Outdated
def is_number (Data): | ||
""" | ||
Data가 숫자인지 확인하는 함수. | ||
숫자가 아니면 ValueError를 발생시킴. | ||
""" | ||
try: | ||
str(Data) # Data가 int 형식인지 확인 | ||
except ValueError as e: | ||
raise ValueError("숫자만 입력해주세요.") from e # 숫자가 아닌 값 입력시 예외 처리 |
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.
함수 로직과 스타일 개선이 필요합니다.
다음과 같은 문제점들이 있습니다:
- 숫자 검증 로직이 부적절합니다 -
str()
은 문자열 변환만 확인하고 실제 숫자 여부는 확인하지 않습니다 - PEP8 스타일 가이드를 준수하지 않습니다
아래와 같이 수정해주세요:
-def is_number (Data):
+def is_number(data):
"""
Data가 숫자인지 확인하는 함수.
숫자가 아니면 ValueError를 발생시킴.
"""
try:
- str(Data) # Data가 int 형식인지 확인
+ int(data) # 문자열을 정수로 변환 시도
except ValueError as e:
raise ValueError("숫자만 입력해주세요.") from e
📝 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.
def is_number (Data): | |
""" | |
Data가 숫자인지 확인하는 함수. | |
숫자가 아니면 ValueError를 발생시킴. | |
""" | |
try: | |
str(Data) # Data가 int 형식인지 확인 | |
except ValueError as e: | |
raise ValueError("숫자만 입력해주세요.") from e # 숫자가 아닌 값 입력시 예외 처리 | |
def is_number(data): | |
""" | |
Data가 숫자인지 확인하는 함수. | |
숫자가 아니면 ValueError를 발생시킴. | |
""" | |
try: | |
int(data) # 문자열을 정수로 변환 시도 | |
except ValueError as e: | |
raise ValueError("숫자만 입력해주세요.") from e |
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 10-11: src/racingcar/main.py#L10-L11
Added lines #L10 - L11 were not covered by tests
🪛 GitHub Actions: Check PEP8 Style
[error] 3-3: E302 expected 2 blank lines, found 1
[error] 3-3: E211 whitespace before '('
src/racingcar/main.py
Outdated
def main(): | ||
""" | ||
프로그램의 진입점 함수. | ||
여기에서 전체 프로그램 로직을 시작합니다. | ||
""" | ||
# 프로그램의 메인 로직을 여기에 구현 | ||
print("프로그램이 시작되었습니다.") | ||
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | ||
name_list = validate_input(list(map(str, input().split(",")))) | ||
n = try_input() | ||
print() | ||
print("실행 결과") | ||
|
||
for i in range(n): | ||
name_list = play_1set_of_game(name_list) | ||
for i in range(len(name_list)): | ||
print("{0} : {1}".format(name_list[i][0], "-" * name_list[i][1])) | ||
print() | ||
|
||
win_list = check_winner(name_list) | ||
|
||
print("최종 우승자 : {0}".format(', '.join(win_list))) | ||
|
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
메인 함수의 개선이 필요합니다.
- 에러 처리가 누락되었습니다
- 출력 메시지가 더 상세할 수 있습니다
- 불필요한 공백 라인이 있습니다
아래와 같이 수정을 제안합니다:
def main():
"""
프로그램의 진입점 함수.
여기에서 전체 프로그램 로직을 시작합니다.
"""
- # 프로그램의 메인 로직을 여기에 구현
- print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
- name_list = validate_input(list(map(str, input().split(","))))
- n = try_input()
- print()
- print("실행 결과")
+ try:
+ print("경주할 자동차 이름을 입력하세요 (이름은 쉼표로 구분)")
+ name_list = validate_input(list(map(str, input().strip().split(","))))
+
+ n = try_input()
+ print("\n실행 결과")
- for i in range(n):
- name_list = play_1set_of_game(name_list)
- for i in range(len(name_list)):
- print("{0} : {1}".format(name_list[i][0], "-" * name_list[i][1]))
- print()
+ for _ in range(n):
+ name_list = play_game_round(name_list)
+ for name, score in name_list:
+ print(f"{name} : {'-' * score}")
+ print()
- win_list = check_winner(name_list)
-
- print("최종 우승자 : {0}".format(', '.join(win_list)))
+ win_list = check_winner(name_list)
+ print(f"최종 우승자 : {', '.join(win_list)}")
+ except ValueError as e:
+ print(f"오류: {e}")
+ return 1
+ return 0
📝 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.
def main(): | |
""" | |
프로그램의 진입점 함수. | |
여기에서 전체 프로그램 로직을 시작합니다. | |
""" | |
# 프로그램의 메인 로직을 여기에 구현 | |
print("프로그램이 시작되었습니다.") | |
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | |
name_list = validate_input(list(map(str, input().split(",")))) | |
n = try_input() | |
print() | |
print("실행 결과") | |
for i in range(n): | |
name_list = play_1set_of_game(name_list) | |
for i in range(len(name_list)): | |
print("{0} : {1}".format(name_list[i][0], "-" * name_list[i][1])) | |
print() | |
win_list = check_winner(name_list) | |
print("최종 우승자 : {0}".format(', '.join(win_list))) | |
def main(): | |
""" | |
프로그램의 진입점 함수. | |
여기에서 전체 프로그램 로직을 시작합니다. | |
""" | |
try: | |
print("경주할 자동차 이름을 입력하세요 (이름은 쉼표로 구분)") | |
name_list = validate_input(list(map(str, input().strip().split(",")))) | |
n = try_input() | |
print("\n실행 결과") | |
for _ in range(n): | |
name_list = play_game_round(name_list) | |
for name, score in name_list: | |
print(f"{name} : {'-' * score}") | |
print() | |
win_list = check_winner(name_list) | |
print(f"최종 우승자 : {', '.join(win_list)}") | |
except ValueError as e: | |
print(f"오류: {e}") | |
return 1 | |
return 0 |
🧰 Tools
🪛 GitHub Actions: Check Indentation Depth
[warning] 62-62: Trailing whitespace
🪛 GitHub Actions: Check PEP8 Style
[warning] 62-62: W293 blank line contains whitespace
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
♻️ Duplicate comments (2)
src/racingcar/main.py (2)
4-13
: 숫자 검증 로직이 올바르지 않습니다.
str()
은 이미 문자열인 입력값을 다시 문자열로 변환하는 것이므로 숫자 여부를 확인할 수 없습니다.다음과 같이 수정해주세요:
-def is_number(Data): +def is_number(data): """ Data가 숫자인지 확인하는 함수. 숫자가 아니면 ValueError를 발생시킴. """ try: - str(Data) # Data가 int 형식인지 확인 + int(data) # 문자열을 정수로 변환 시도 except ValueError as e: raise ValueError("숫자만 입력해주세요.") from e
48-68
: 메인 함수의 에러 처리와 가독성을 개선해주세요.
- 예외 처리가 누락되어 있습니다.
- 변수명이 명확하지 않습니다 (i, n).
- f-string을 사용하여 문자열 포매팅을 개선할 수 있습니다.
다음과 같이 수정해주세요:
def main(): - print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") - name_list = validate_input(list(map(str, input().split(",")))) - n = try_input() - print() - print("실행 결과") + try: + print("경주할 자동차 이름을 입력하세요 (이름은 쉼표로 구분)") + cars = validate_input(list(map(str, input().strip().split(",")))) + + attempts = try_input() + print("\n실행 결과") - for i in range(n): - name_list = play_1set_of_game(name_list) - for i in range(len(name_list)): - print("{0} : {1}".format(name_list[i][0], "-" * name_list[i][1])) - print() + for _ in range(attempts): + cars = play_1set_of_game(cars) + for car_name, distance in cars: + print(f"{car_name} : {'-' * distance}") + print() - win_list = check_winner(name_list) - print("최종 우승자 : {0}".format(', '.join(win_list))) + winners = check_winner(cars) + print(f"최종 우승자 : {', '.join(winners)}") + except ValueError as e: + print(f"오류: {e}") + return 1 + return 0
🧹 Nitpick comments (2)
src/racingcar/main.py (2)
1-3
: 불필요한 빈 줄을 제거해주세요.PEP 8 스타일 가이드에 따르면 모듈 레벨 import문 다음에는 한 줄의 공백만 있어야 합니다.
import random -
30-35
: 매직 넘버를 상수로 분리해주세요.코드의 가독성과 유지보수성을 높이기 위해 매직 넘버(4, 10)를 의미 있는 상수로 분리하는 것이 좋습니다.
다음과 같이 수정해주세요:
+RANDOM_RANGE_MAX = 10 +FORWARD_THRESHOLD = 4 def play_1set_of_game(Data): for i in range(len(Data)): - value = random.randint(0, 10) - if value >= 4: + value = random.randint(0, RANDOM_RANGE_MAX) + if value >= FORWARD_THRESHOLD: Data[i][1] += 1 return Data
62번줄, 65번줄 trailing-whitespace
PEP8 Style로 코드 변경
PEP8 Style로 코드 변경
int형인지 검사해야하지만, str형인지로 검사하는 오류
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
♻️ Duplicate comments (1)
src/racingcar/main.py (1)
48-68
: 메인 함수의 에러 처리와 구현을 개선해주세요.이전 리뷰에서 지적된 문제점들이 아직 해결되지 않았습니다:
- 에러 처리 누락
- 중첩된 루프에서 동일한 변수 'i' 사용
다음과 같이 수정을 제안합니다:
def main(): - print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") - name_list = validate_input(list(map(str, input().split(",")))) - n = try_input() - print() - print("실행 결과") - - for i in range(n): - name_list = play_1set_of_game(name_list) - for i in range(len(name_list)): - print("{0} : {1}".format(name_list[i][0], "-" * name_list[i][1])) - print() - - win_list = check_winner(name_list) - - print("최종 우승자 : {0}".format(', '.join(win_list))) + try: + print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") + name_list = validate_input(list(map(str, input().strip().split(",")))) + n = try_input() + print("\n실행 결과") + + for round_num in range(n): + name_list = play_game_round(name_list) + for car in name_list: + print(f"{car[0]} : {'-' * car[1]}") + print() + + win_list = check_winner(name_list) + print(f"최종 우승자 : {', '.join(win_list)}") + return 0 + except ValueError as e: + print(f"오류: {e}") + return 1
🧹 Nitpick comments (2)
src/racingcar/main.py (2)
30-35
: 함수 이름과 구현을 개선해주세요.개선이 필요한 부분들:
- 함수 이름이 Python 명명 규칙을 따르지 않습니다
- 매직 넘버(4, 10)를 상수로 분리하면 좋겠습니다
다음과 같이 수정을 제안합니다:
+FORWARD_THRESHOLD = 4 +MAX_RANDOM_VALUE = 10 + -def play_1set_of_game(Data): +def play_game_round(Data): for i in range(len(Data)): - value = random.randint(0, 10) - if value >= 4: + value = random.randint(0, MAX_RANDOM_VALUE) + if value >= FORWARD_THRESHOLD: Data[i][1] += 1 return Data
38-45
: 승자 확인 로직을 더 효율적으로 개선할 수 있습니다.현재 구현을 더 파이썬스럽고 효율적으로 개선할 수 있습니다.
다음과 같이 수정을 제안합니다:
def check_winner(Data): - win_list, winner_count = list(), 0 - for i in range(len(Data)): - if Data[i][1] > winner_count: - win_list, winner_count = [Data[i][0]], Data[i][1] - elif Data[i][1] == winner_count: - win_list.append(Data[i][0]) - return win_list + if not Data: + return [] + max_score = max(car[1] for car in Data) + return [car[0] for car in Data if car[1] == max_score]
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/racingcar/main.py
(1 hunks)
🔇 Additional comments (1)
src/racingcar/main.py (1)
4-12
: 구현이 개선되었습니다!이전 리뷰의 피드백이 잘 반영되어 있습니다:
int()
함수를 사용하여 올바른 숫자 검증- 명확한 예외 처리
- PEP8 스타일 가이드 준수
src/racingcar/main.py
Outdated
def try_input(): | ||
print("시도할 횟수는 몇 회인가요?") | ||
n = input() | ||
is_number(n) | ||
return int(n) |
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 입력 방지
- 최대 시도 횟수 제한
다음과 같이 수정을 제안합니다:
def try_input():
print("시도할 횟수는 몇 회인가요?")
n = input()
is_number(n)
- return int(n)
+ n = int(n)
+ if n <= 0:
+ raise ValueError("시도 횟수는 1 이상이어야 합니다.")
+ if n > 100: # 적절한 상한선 설정
+ raise ValueError("시도 횟수가 너무 많습니다. (최대: 100)")
+ return n
📝 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.
def try_input(): | |
print("시도할 횟수는 몇 회인가요?") | |
n = input() | |
is_number(n) | |
return int(n) | |
def try_input(): | |
print("시도할 횟수는 몇 회인가요?") | |
n = input() | |
is_number(n) | |
n = int(n) | |
if n <= 0: | |
raise ValueError("시도 횟수는 1 이상이어야 합니다.") | |
if n > 100: # 적절한 상한선 설정 | |
raise ValueError("시도 횟수가 너무 많습니다. (최대: 100)") | |
return n |
src/racingcar/main.py
Outdated
def validate_input(Data): | ||
for i in range(len(Data)): | ||
if len(Data[i]) > 5: | ||
raise ValueError("이름은 5자 이하만 가능합니다.") | ||
Data[i] = [Data[i], 0] | ||
return Data |
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
입력 검증 로직을 개선해주세요.
현재 구현에서 개선이 필요한 부분들이 있습니다:
- 빈 입력이나 빈 이름에 대한 검증이 없습니다
- 파이썬스러운 방식으로 개선할 수 있습니다
다음과 같이 수정을 제안합니다:
def validate_input(Data):
+ if not Data:
+ raise ValueError("자동차 이름을 입력해주세요.")
+
- for i in range(len(Data)):
- if len(Data[i]) > 5:
+ for name in Data:
+ if not name.strip():
+ raise ValueError("빈 이름은 허용되지 않습니다.")
+ if len(name) > 5:
raise ValueError("이름은 5자 이하만 가능합니다.")
- Data[i] = [Data[i], 0]
- return Data
+ return [[name, 0] for name in Data]
📝 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.
def validate_input(Data): | |
for i in range(len(Data)): | |
if len(Data[i]) > 5: | |
raise ValueError("이름은 5자 이하만 가능합니다.") | |
Data[i] = [Data[i], 0] | |
return Data | |
def validate_input(Data): | |
if not Data: | |
raise ValueError("자동차 이름을 입력해주세요.") | |
for name in Data: | |
if not name.strip(): | |
raise ValueError("빈 이름은 허용되지 않습니다.") | |
if len(name) > 5: | |
raise ValueError("이름은 5자 이하만 가능합니다.") | |
return [[name, 0] for name in Data] |
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.
전반적으로 잘 하셨어요.
요구사항에 맞춰 조금만 더 코드를 개선해봅시당~
src/racingcar/main.py
Outdated
import random | ||
|
||
|
||
def is_number(Data): |
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.
pameter는 소문자로 시작하는 것이 권장됩니다.
Editer의 리팩토링-Rename
기능으로 수정해보시죠.
src/racingcar/main.py
Outdated
def validate_input(Data): | ||
for i in range(len(Data)): | ||
if len(Data[i]) > 5: | ||
raise ValueError("이름은 5자 이하만 가능합니다.") | ||
Data[i] = [Data[i], 0] | ||
return Data |
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.
빈 이름에 대한 검증이 힘들 것 같네요.
src/racingcar/main.py
Outdated
|
||
def try_input(): | ||
print("시도할 횟수는 몇 회인가요?") | ||
n = input() |
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.
코딩테스트가 아닌 경우에는 변수명을 더 명확히 작성해주는 것이 좋습니다.
src/racingcar/main.py
Outdated
def try_input(): | ||
print("시도할 횟수는 몇 회인가요?") | ||
n = input() | ||
is_number(n) | ||
return int(n) |
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.
시도 횟수에 대한 추가 검증이 있다면 좋을 것 같네요.
src/racingcar/main.py
Outdated
for i in range(len(name_list)): | ||
print("{0} : {1}".format(name_list[i][0], "-" * name_list[i][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.
함수로 바꾸는 게 더 가독성이 좋을 것 같습니다.
src/racingcar/main.py
Outdated
def play_1set_of_game(Data): | ||
for i in range(len(Data)): | ||
value = random.randint(0, 10) | ||
if value >= 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.
숫자상수는, 매직넘버상수로 바꾸고 전방선언 해주는 것이 좋습니다.
게임 실행 결과가 출력되는 기능을 main()으로부터 'print_game_play_result()'라는 함수로 분리
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
♻️ Duplicate comments (1)
src/racingcar/main.py (1)
15-20
: 🛠️ Refactor suggestion입력 검증과 Python 스타일을 개선해주세요.
- 빈 입력에 대한 검증이 필요합니다
- Python의 리스트 컴프리헨션을 활용하면 더 간결해질 수 있습니다
def validate_input(Data): + if not Data: + raise ValueError("자동차 이름을 입력해주세요.") - for i in range(len(Data)): - if len(Data[i]) > 5: + for name in Data: + if len(name.strip()) > 5: raise ValueError("이름은 5자 이하만 가능합니다.") - Data[i] = [Data[i], 0] - return Data + return [[name.strip(), 0] for name in Data]
🧹 Nitpick comments (2)
src/racingcar/main.py (2)
38-45
: Python의 내장 함수를 활용해 코드를 개선해주세요.max() 함수와 리스트 컴프리헨션을 활용하면 더 간결하고 읽기 쉬운 코드가 됩니다.
def check_winner(Data): - win_list, winner_count = list(), 0 - for i in range(len(Data)): - if Data[i][1] > winner_count: - win_list, winner_count = [Data[i][0]], Data[i][1] - elif Data[i][1] == winner_count: - win_list.append(Data[i][0]) - return win_list + max_score = max(car[1] for car in Data) + return [car[0] for car in Data if car[1] == max_score]
48-54
: 출력 형식을 개선하고 함수 책임을 분리해주세요.
- f-string을 사용하면 더 읽기 쉽습니다
- 출력과 게임 진행 로직을 분리하는 것이 좋습니다
-def print_game_play_result(Data, n): +def print_game_progress(cars): + for car_name, distance in cars: + print(f"{car_name} : {'-' * distance}") + print() + +def simulate_game(cars, rounds): for i in range(n): - Data = play_1set_of_game(Data) - for i in range(len(Data)): - print("{0} : {1}".format(Data[i][0], "-" * Data[i][1])) - print() - return Data + cars = play_game_round(cars) + print_game_progress(cars) + return cars
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/racingcar/main.py
(1 hunks)
🔇 Additional comments (2)
src/racingcar/main.py (2)
4-12
: 매개변수 이름을 Python 명명 규칙에 맞게 수정해주세요.Python 명명 규칙에 따라 매개변수 이름은 소문자로 시작해야 합니다.
-def is_number(Data): +def is_number(data): """ - Data가 숫자인지 확인하는 함수. + data가 숫자인지 확인하는 함수. 숫자가 아니면 ValueError를 발생시킴. """ try: - int(Data) # Data가 int 형식인지 확인 + int(data) # data가 int 형식인지 확인 except ValueError as e: raise ValueError("숫자만 입력해주세요.") from e
23-27
: 시도 횟수에 대한 유효성 검사를 추가해주세요.음수, 0, 그리고 너무 큰 값에 대한 검증이 필요합니다.
def try_input(): print("시도할 횟수는 몇 회인가요?") n = input() is_number(n) - return int(n) + n = int(n) + if n <= 0: + raise ValueError("시도 횟수는 1 이상이어야 합니다.") + MAX_ATTEMPTS = 100 # 상수로 정의 + if n > MAX_ATTEMPTS: + raise ValueError(f"시도 횟수가 너무 많습니다. (최대: {MAX_ATTEMPTS})") + return n
src/racingcar/main.py
Outdated
def play_1set_of_game(Data): | ||
for i in range(len(Data)): | ||
value = random.randint(0, 10) | ||
if value >= 4: | ||
Data[i][1] += 1 | ||
return Data |
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
상수 정의와 Python 스타일을 개선해주세요.
- 매직 넘버를 상수로 정의해주세요
- Python 스타일의 반복문을 사용해주세요
- 함수 이름을 더 명확하게 해주세요
+# 상수 정의
+RANDOM_MAX = 10
+FORWARD_THRESHOLD = 4
+
-def play_1set_of_game(Data):
+def play_game_round(cars):
- for i in range(len(Data)):
- value = random.randint(0, 10)
- if value >= 4:
- Data[i][1] += 1
- return Data
+ for car in cars:
+ if random.randint(0, RANDOM_MAX) >= FORWARD_THRESHOLD:
+ car[1] += 1
+ return cars
📝 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.
def play_1set_of_game(Data): | |
for i in range(len(Data)): | |
value = random.randint(0, 10) | |
if value >= 4: | |
Data[i][1] += 1 | |
return Data | |
RANDOM_MAX = 10 | |
FORWARD_THRESHOLD = 4 | |
def play_game_round(cars): | |
for car in cars: | |
if random.randint(0, RANDOM_MAX) >= FORWARD_THRESHOLD: | |
car[1] += 1 | |
return cars |
src/racingcar/main.py
Outdated
def main(): | ||
""" | ||
프로그램의 진입점 함수. | ||
여기에서 전체 프로그램 로직을 시작합니다. | ||
""" | ||
# 프로그램의 메인 로직을 여기에 구현 | ||
print("프로그램이 시작되었습니다.") | ||
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | ||
name_list = validate_input(list(map(str, input().split(",")))) | ||
n = try_input() | ||
print() | ||
print("실행 결과") | ||
|
||
win_list = check_winner(print_game_play_result(name_list, n)) | ||
|
||
print("최종 우승자 : {0}".format(', '.join(win_list))) |
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
메인 함수에 예외 처리와 입력 정제를 추가해주세요.
- 예외 처리를 추가하여 프로그램의 안정성을 높여주세요
- 입력값 정제를 추가해주세요
def main():
- print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
- name_list = validate_input(list(map(str, input().split(","))))
- n = try_input()
- print()
- print("실행 결과")
-
- win_list = check_winner(print_game_play_result(name_list, n))
-
- print("최종 우승자 : {0}".format(', '.join(win_list)))
+ try:
+ print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
+ raw_input = input().strip()
+ name_list = validate_input(list(map(str.strip, raw_input.split(","))))
+
+ n = try_input()
+ print("\n실행 결과")
+
+ final_state = simulate_game(name_list, n)
+ win_list = check_winner(final_state)
+
+ print(f"최종 우승자 : {', '.join(win_list)}")
+ return 0
+ except ValueError as e:
+ print(f"오류: {e}")
+ return 1
Committable suggestion skipped: line range outside the PR's diff.
대문자로 시작하는 파라미터를 소문자로 시작하도록 변경
빈 이름에 대한 검증 추가 중복되는 이름에 대한 검증 추가가
변수명을 더 정확히 작성 (n -> try_number)
변수명을 더 정확히 작성 (n -> try_number)
시도 횟수에 대한 검증 추가 (양의 정수가 아니면 ValueError 발생)
숫자 상수를 매직넘버 상수로 바꾸고, 전방선언 PEP8 Style로 코드 변경
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
♻️ Duplicate comments (1)
src/racingcar/main.py (1)
74-89
: 🛠️ Refactor suggestion예외 처리를 추가해주세요.
메인 함수에 예외 처리를 추가하여 프로그램의 안정성을 높여주세요:
def main(): + try: print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)") # ... 기존 코드 ... print("최종 우승자 : {0}".format(', '.join(win_list))) + return 0 + except ValueError as e: + print(f"오류: {e}") + return 1🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 81-81: E231 missing whitespace after ','
[error] 81-81: E501 line too long (82 > 79 characters)
🧹 Nitpick comments (4)
src/racingcar/main.py (4)
4-5
: 상수 이름을 더 명확하게 개선해주세요.상수의 의미를 더 잘 전달하기 위해 다음과 같이 이름을 변경하는 것을 제안합니다:
-THRESHOLD = 4 # 성공 기준 값 -MAX_RANDOM_VALUE = 10 # 랜덤 숫자의 최대값 +FORWARD_THRESHOLD = 4 # 자동차 전진 기준 값 +MAX_RANDOM_RANGE = 10 # 랜덤 범위의 최대값
19-28
: 코드를 더 파이썬스럽게 개선할 수 있습니다.현재 구현을 더 간결하고 효율적으로 만들 수 있습니다:
def validate_name(data): + seen = set() for i in range(len(data)): - if len(data[i]) > 5: + name = data[i] + if len(name) > 5: raise ValueError("이름은 5자 이하만 가능합니다.") - elif len(data[i]) == 0: + elif not name: raise ValueError("이름은 빈칸일 수 없습니다.") - elif data.count(data[i]) != 1: + elif name in seen: raise ValueError("중복되는 이름이 있습니다.") - data[i] = [data[i], 0] + seen.add(name) + data[i] = [name, 0]🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 24-24: src/racingcar/main.py#L24
Added line #L24 was not covered by tests
[warning] 26-26: src/racingcar/main.py#L26
Added line #L26 was not covered by tests
30-38
: 타입 힌트를 추가하면 좋겠습니다.함수의 입력과 출력 타입을 명확히 하기 위해 타입 힌트를 추가하는 것을 제안합니다:
-def validate_input(data): +def validate_input(data: Union[str, List[str]]) -> Union[str, List[List[str, int]]]:이를 위해 파일 상단에 다음 import를 추가해주세요:
from typing import Union, List🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 34-34: src/racingcar/main.py#L34
Added line #L34 was not covered by tests
47-53
: 함수 이름과 구현을 개선할 수 있습니다.
- 함수 이름을 더 명확하게 변경하고
- 구현을 더 파이썬스럽게 개선하는 것을 제안합니다:
-def play_1set_of_game(data): +def simulate_game_round(cars): - for i in range(len(data)): - value = random.randint(0, MAX_RANDOM_VALUE) - if value >= THRESHOLD: - data[i][1] += 1 - return data + for car in cars: + if random.randint(0, MAX_RANDOM_VALUE) >= THRESHOLD: + car[1] += 1 + return cars
📜 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] 15-16: src/racingcar/main.py#L15-L16
Added lines #L15 - L16 were not covered by tests
[warning] 24-24: src/racingcar/main.py#L24
Added line #L24 was not covered by tests
[warning] 26-26: src/racingcar/main.py#L26
Added line #L26 was not covered by tests
[warning] 34-34: src/racingcar/main.py#L34
Added line #L34 was not covered by tests
[warning] 61-61: src/racingcar/main.py#L61
Added line #L61 was not covered by tests
[warning] 93-93: src/racingcar/main.py#L93
Added line #L93 was not covered by tests
🪛 GitHub Actions: Check Indentation Depth
src/racingcar/main.py
[warning] 93-93: Final newline missing (missing-final-newline)
🪛 GitHub Actions: Check PEP8 Style
src/racingcar/main.py
[error] 81-81: E231 missing whitespace after ','
[error] 81-81: E501 line too long (82 > 79 characters)
[warning] 93-93: W292 no newline at end of file
🔇 Additional comments (3)
src/racingcar/main.py (3)
8-17
: 구현이 잘 되었습니다!숫자 검증 로직이 명확하고 예외 처리가 잘 구현되어 있습니다.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 15-16: src/racingcar/main.py#L15-L16
Added lines #L15 - L16 were not covered by tests
19-28
: 테스트 커버리지를 개선해주세요.예외 케이스에 대한 테스트가 누락되어 있습니다. 다음 테스트 케이스들을 추가해주세요:
- 이름이 5자를 초과하는 경우
- 이름이 비어있는 경우
- 중복된 이름이 있는 경우
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 24-24: src/racingcar/main.py#L24
Added line #L24 was not covered by tests
[warning] 26-26: src/racingcar/main.py#L26
Added line #L26 was not covered by tests
1-93
: 테스트 커버리지를 전반적으로 개선해주세요.다음 부분들에 대한 테스트가 누락되어 있습니다:
- ValueError 예외 발생 케이스들
- 공동 우승자가 있는 경우
- 최소/최대 시도 횟수 케이스
테스트 파일에 이러한 케이스들을 추가하여 코드의 신뢰성을 높여주세요.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 15-16: src/racingcar/main.py#L15-L16
Added lines #L15 - L16 were not covered by tests
[warning] 24-24: src/racingcar/main.py#L24
Added line #L24 was not covered by tests
[warning] 26-26: src/racingcar/main.py#L26
Added line #L26 was not covered by tests
[warning] 34-34: src/racingcar/main.py#L34
Added line #L34 was not covered by tests
[warning] 61-61: src/racingcar/main.py#L61
Added line #L61 was not covered by tests
[warning] 93-93: src/racingcar/main.py#L93
Added line #L93 was not covered by tests🪛 GitHub Actions: Check Indentation Depth
[warning] 93-93: Final newline missing (missing-final-newline)
🪛 GitHub Actions: Check PEP8 Style
[error] 81-81: E231 missing whitespace after ','
[error] 81-81: E501 line too long (82 > 79 characters)
[warning] 93-93: W292 no newline at end of file
src/racingcar/main.py
Outdated
if __name__ == "__main__": | ||
# 프로그램이 직접 실행될 때만 main() 함수를 호출 | ||
main() | ||
main() |
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
파일 끝에 개행을 추가해주세요.
PEP8 스타일 가이드를 준수하기 위해 파일 끝에 빈 줄을 추가해주세요.
if __name__ == "__main__":
# 프로그램이 직접 실행될 때만 main() 함수를 호출
- main()
+ main()
+
📝 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.
if __name__ == "__main__": | |
# 프로그램이 직접 실행될 때만 main() 함수를 호출 | |
main() | |
main() | |
if __name__ == "__main__": | |
# 프로그램이 직접 실행될 때만 main() 함수를 호출 | |
main() | |
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 93-93: src/racingcar/main.py#L93
Added line #L93 was not covered by tests
🪛 GitHub Actions: Check Indentation Depth
[warning] 93-93: Final newline missing (missing-final-newline)
🪛 GitHub Actions: Check PEP8 Style
[warning] 93-93: W292 no newline at end of file
src/racingcar/main.py
Outdated
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | ||
name_list = validate_input(list(map(str, input().replace(" ","").split(",")))) | ||
try_number = try_input() |
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
입력 처리와 PEP8 스타일을 개선해주세요.
- 입력 문자열 처리를 개선하고
- PEP8 스타일 가이드를 준수하도록 수정이 필요합니다:
- print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
- name_list = validate_input(list(map(str, input().replace(" ","").split(","))))
+ print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)")
+ raw_input = input().strip()
+ name_list = validate_input([name.strip() for name in raw_input.split(",")])
📝 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.
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | |
name_list = validate_input(list(map(str, input().replace(" ","").split(",")))) | |
try_number = try_input() | |
print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)") | |
raw_input = input().strip() | |
name_list = validate_input([name.strip() for name in raw_input.split(",")]) | |
try_number = try_input() |
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style
[error] 81-81: E231 missing whitespace after ','
[error] 81-81: E501 line too long (82 > 79 characters)
아래 스타일 오류 수정 src/racingcar/main.py:81:65: E231 missing whitespace after ',' src/racingcar/main.py:81:80: E501 line too long (82 > 79 characters) src/racingcar/main.py:93:11: W292 no newline at end of file
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
♻️ Duplicate comments (1)
src/racingcar/main.py (1)
74-89
: 🛠️ Refactor suggestion메인 함수의 예외 처리와 입력 처리를 개선해주세요.
예외 처리를 추가하고 입력 처리를 더 견고하게 만들 수 있습니다:
def main(): - print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") - get_name = input().replace(" ", "").split(",") - name_list = validate_input(list(map(str, get_name))) - try_number = try_input() - print() - print("실행 결과") - - win_list = check_winner(print_game_play_result(name_list, try_number)) - - print("최종 우승자 : {0}".format(', '.join(win_list))) + try: + print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)") + raw_input = input().strip() + name_list = validate_input([name.strip() for name in raw_input.split(",")]) + + try_number = try_input() + print("\n실행 결과") + + final_state = simulate_game(name_list, try_number) + winners = check_winner(final_state) + + print(f"최종 우승자 : {', '.join(winners)}") + return 0 + except ValueError as e: + print(f"오류: {e}") + return 1
🧹 Nitpick comments (6)
src/racingcar/main.py (6)
4-5
: 상수 이름을 더 명확하게 개선해주세요.상수의 의미를 더 명확하게 전달하기 위해 이름을 개선하면 좋겠습니다:
-THRESHOLD = 4 # 성공 기준 값 -MAX_RANDOM_VALUE = 10 # 랜덤 숫자의 최대값 +FORWARD_THRESHOLD = 4 # 전진 기준 값 +MAX_RANDOM_RANGE = 10 # 랜덤 범위의 최대값
19-28
: 더 파이썬스러운 방식으로 개선해주세요.현재 구현은 잘 작동하지만, 더 파이썬스러운 방식으로 개선할 수 있습니다:
def validate_name(data): + if not data: + raise ValueError("이름 목록이 비어있습니다.") + + # 중복 검사를 set으로 한 번에 수행 + if len(set(data)) != len(data): + raise ValueError("중복되는 이름이 있습니다.") + - for i in range(len(data)): - if len(data[i]) > 5: - raise ValueError("이름은 5자 이하만 가능합니다.") - elif len(data[i]) == 0: - raise ValueError("이름은 빈칸일 수 없습니다.") - elif data.count(data[i]) != 1: - raise ValueError("중복되는 이름이 있습니다.") - data[i] = [data[i], 0] + for name in data: + if not name: + raise ValueError("이름은 빈칸일 수 없습니다.") + if len(name) > 5: + raise ValueError("이름은 5자 이하만 가능합니다.") + + return [[name, 0] for name in data]
47-53
: 함수 이름과 구현을 개선해주세요.함수 이름과 구현을 더 명확하고 파이썬스럽게 개선할 수 있습니다:
-def play_1set_of_game(data): +def play_game_round(cars): - for i in range(len(data)): - value = random.randint(0, MAX_RANDOM_VALUE) - if value >= THRESHOLD: - data[i][1] += 1 - return data + return [[name, score + 1] if random.randint(0, MAX_RANDOM_RANGE) >= FORWARD_THRESHOLD + else [name, score] + for name, score in cars]
55-63
: 승자 확인 로직을 더 간단하게 개선해주세요.max()와 리스트 컴프리헨션을 활용하여 더 간단하게 구현할 수 있습니다:
def check_winner(data): - win_list, winner_count = list(), 0 - for i in range(len(data)): - if data[i][1] > winner_count: - win_list, winner_count = [data[i][0]], data[i][1] - elif data[i][1] == winner_count: - win_list.append(data[i][0]) - return win_list + max_score = max(score for _, score in data) + return [name for name, score in data if score == max_score]
65-72
: 게임 진행과 출력 로직을 분리해주세요.게임 진행과 출력을 별도의 함수로 분리하고, f-string을 사용하여 가독성을 개선할 수 있습니다:
-def print_game_play_result(data, try_number): +def simulate_game(cars, rounds): + """게임을 진행하고 각 라운드의 결과를 출력합니다.""" for i in range(try_number): - data = play_1set_of_game(data) - for i in range(len(data)): - print("{0} : {1}".format(data[i][0], "-" * data[i][1])) + cars = play_game_round(cars) + display_round_result(cars) print() - return data + return cars + +def display_round_result(cars): + """한 라운드의 결과를 출력합니다.""" + for name, score in cars: + print(f"{name} : {'-' * score}")
1-95
: 파일 구조를 PEP8에 맞게 개선해주세요.
- 함수 사이의 빈 줄을 2줄로 통일해주세요
- 파일 끝에 빈 줄을 추가해주세요
또한 각 함수에 대한 문서화 문자열(docstring)을 추가하면 좋겠습니다.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/racingcar/main.py
(1 hunks)
🔇 Additional comments (1)
src/racingcar/main.py (1)
8-17
: 구현이 잘 되었습니다!숫자 검증 로직이 이전 피드백을 반영하여 잘 개선되었습니다.
시도 횟수 입력에 대한 검증 방법 변경 validate_input()에 instance를 str로 가져온 다음 is_number()로 검증 후 양의 정수인지 확인하는 방법 -> try_input()에서 is_number()로 검증 후 validate_input()에 instance를 int형으로 보내어 코드 가독성을 높임
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 (7)
src/racingcar/main.py (7)
4-5
: 상수 정의를 개선해주세요.
- 타입 힌트를 추가하면 코드의 가독성이 향상됩니다.
- 상수 이름을 더 명확하게 지을 수 있습니다.
-THRESHOLD = 4 # 성공 기준 값 -MAX_RANDOM_VALUE = 10 # 랜덤 숫자의 최대값 +FORWARD_THRESHOLD: int = 4 # 자동차 전진 기준 값 +MAX_RANDOM_VALUE: int = 10 # 랜덤 숫자의 최대값
9-12
: 문서 문자열을 개선해주세요.함수의 입력값, 반환값, 예외 상황에 대한 설명을 추가하면 좋겠습니다.
- """ - data가 숫자인지 확인하는 함수. - 숫자가 아니면 ValueError를 발생시킴. - """ + """숫자 유효성을 검사하고 정수로 변환하는 함수 + + Args: + data: 검사할 입력값 + + Returns: + int: 변환된 정수값 + + Raises: + ValueError: 입력값이 정수로 변환될 수 없는 경우 + """
19-28
: 함수 구현을 더 파이썬스럽게 개선해주세요.
- 리스트 컴프리헨션을 사용하면 코드가 더 간결해집니다.
- 입력값을 직접 수정하는 대신 새로운 리스트를 반환하는 것이 더 좋습니다.
def validate_name(data): + # 유효성 검사 for i in range(len(data)): - if len(data[i]) > 5: + name = data[i].strip() + if len(name) > 5: raise ValueError("이름은 5자 이하만 가능합니다.") - elif len(data[i]) == 0: + elif not name: raise ValueError("이름은 빈칸일 수 없습니다.") - elif data.count(data[i]) != 1: + elif data.count(name) != 1: raise ValueError("중복되는 이름이 있습니다.") - data[i] = [data[i], 0] - + + # 검증된 데이터로 새로운 리스트 생성 + return [[name.strip(), 0] for name in data]
47-53
: 게임 라운드 함수를 개선해주세요.
- 함수 이름을 더 명확하게 변경하면 좋겠습니다.
enumerate
를 사용하면 더 파이썬스럽게 구현할 수 있습니다.-def play_1set_of_game(data): +def play_game_round(cars): - for i in range(len(data)): - value = random.randint(0, MAX_RANDOM_VALUE) - if value >= THRESHOLD: - data[i][1] += 1 - return data + for i, car in enumerate(cars): + if random.randint(0, MAX_RANDOM_VALUE) >= FORWARD_THRESHOLD: + cars[i][1] += 1 + return cars
55-63
: 우승자 확인 함수를 개선해주세요.
max()
를 사용하여 최고 점수를 찾을 수 있습니다.- 변수명을 더 명확하게 지을 수 있습니다.
def check_winner(data): - win_list, winner_count = list(), 0 - for i in range(len(data)): - if data[i][1] > winner_count: - win_list, winner_count = [data[i][0]], data[i][1] - elif data[i][1] == winner_count: - win_list.append(data[i][0]) - return win_list + max_score = max(car[1] for car in data) + return [car[0] for car in data if car[1] == max_score]
65-72
: 게임 결과 출력 함수를 개선해주세요.
- f-문자열을 사용하면 가독성이 향상됩니다.
- 중첩된 반복문을 더 간단하게 만들 수 있습니다.
def print_game_play_result(data, try_number): for i in range(try_number): data = play_1set_of_game(data) - for i in range(len(data)): - print("{0} : {1}".format(data[i][0], "-" * data[i][1])) + for name, score in data: + print(f"{name} : {'-' * score}") print() return data
92-94
: 파일 끝에 개행을 추가해주세요.PEP8 스타일 가이드를 준수하기 위해 파일 끝에 빈 줄을 추가해주세요.
if __name__ == "__main__": # 프로그램이 직접 실행될 때만 main() 함수를 호출 - main() + main() +
src/racingcar/main.py
Outdated
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | ||
get_name = input().replace(" ", "").split(",") | ||
name_list = validate_input(list(map(str, get_name))) | ||
try_number = try_input() | ||
print() | ||
print("실행 결과") | ||
|
||
win_list = check_winner(print_game_play_result(name_list, try_number)) | ||
|
||
print("최종 우승자 : {0}".format(', '.join(win_list))) |
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
메인 함수의 오류 처리와 입력 처리를 개선해주세요.
- try-except 블록으로 오류를 처리하면 좋겠습니다.
- 입력값 처리를 더 견고하게 만들 수 있습니다.
- print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
- get_name = input().replace(" ", "").split(",")
- name_list = validate_input(list(map(str, get_name)))
- try_number = try_input()
- print()
- print("실행 결과")
-
- win_list = check_winner(print_game_play_result(name_list, try_number))
-
- print("최종 우승자 : {0}".format(', '.join(win_list)))
+ try:
+ print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)")
+ raw_input = input().strip()
+ name_list = validate_input([name.strip() for name in raw_input.split(",")])
+
+ try_number = try_input()
+ print("\n실행 결과")
+
+ final_state = print_game_play_result(name_list, try_number)
+ win_list = check_winner(final_state)
+
+ print(f"최종 우승자 : {', '.join(win_list)}")
+ return 0
+ except ValueError as e:
+ print(f"오류: {e}")
+ return 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.
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | |
get_name = input().replace(" ", "").split(",") | |
name_list = validate_input(list(map(str, get_name))) | |
try_number = try_input() | |
print() | |
print("실행 결과") | |
win_list = check_winner(print_game_play_result(name_list, try_number)) | |
print("최종 우승자 : {0}".format(', '.join(win_list))) | |
try: | |
print("경주할 자동차 이름을 입력하세요. (이름은 쉼표로 구분)") | |
raw_input = input().strip() | |
name_list = validate_input([name.strip() for name in raw_input.split(",")]) | |
try_number = try_input() | |
print("\n실행 결과") | |
final_state = print_game_play_result(name_list, try_number) | |
win_list = check_winner(final_state) | |
print(f"최종 우승자 : {', '.join(win_list)}") | |
return 0 | |
except ValueError as e: | |
print(f"오류: {e}") | |
return 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: 1
🧹 Nitpick comments (3)
src/racingcar/main.py (3)
2-7
: 불필요한 빈 줄을 제거해주세요.섹션 사이에 빈 줄이 너무 많습니다. PEP8 스타일 가이드에 따르면 두 줄이면 충분합니다.
import random - - THRESHOLD = 4 # 성공 기준 값 MAX_RANDOM_VALUE = 10 # 랜덤 숫자의 최대값 -
19-28
: 입력 검증 로직을 더 파이썬스럽게 개선해주세요.
- 인덱스 기반 반복문 대신
for
문을 사용하면 더 파이썬스럽습니다.- 빈 문자열 검사는
if not name.strip()
으로 단순화할 수 있습니다.- 중복 이름 검사는
set
을 사용하면 더 효율적입니다.def validate_name(data): - for i in range(len(data)): - if len(data[i]) > 5: + names = [name.strip() for name in data] + if len(names) != len(set(names)): + raise ValueError("중복되는 이름이 있습니다.") + + for name in names: + if len(name) > 5: raise ValueError("이름은 5자 이하만 가능합니다.") - elif len(data[i]) == 0: + elif not name: raise ValueError("이름은 빈칸일 수 없습니다.") - elif data.count(data[i]) != 1: - raise ValueError("중복되는 이름이 있습니다.") - data[i] = [data[i], 0] + return [[name, 0] for name in names]
50-56
: 게임 로직 함수를 더 파이썬스럽게 개선해주세요.
- 함수 이름을
play_game_round
로 변경하면 의도가 더 명확해집니다.- 인덱스 기반 반복문 대신
for
문을 사용하면 더 파이썬스럽습니다.-def play_1set_of_game(data): - for i in range(len(data)): - value = random.randint(0, MAX_RANDOM_VALUE) - if value >= THRESHOLD: - data[i][1] += 1 +def play_game_round(cars): + for car in cars: + if random.randint(0, MAX_RANDOM_VALUE) >= THRESHOLD: + car[1] += 1 return data
def main(): | ||
""" | ||
프로그램의 진입점 함수. | ||
여기에서 전체 프로그램 로직을 시작합니다. | ||
""" | ||
# 프로그램의 메인 로직을 여기에 구현 | ||
print("프로그램이 시작되었습니다.") | ||
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | ||
name_list = name_input() | ||
|
||
print("시도할 횟수는 몇 회인가요?") | ||
try_number = try_input() | ||
|
||
print("\n실행 결과") | ||
play_list = print_game_play_result(name_list, try_number) | ||
|
||
win_list = check_winner(play_list) | ||
print("최종 우승자 : {0}".format(', '.join(win_list))) |
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
메인 함수에 예외 처리를 추가하고 문자열 포맷팅을 개선해주세요.
- 사용자 입력에 대한 예외 처리가 필요합니다.
- 문자열 포맷팅을 f-string으로 변경하면 더 읽기 쉽습니다.
def main():
- print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
- name_list = name_input()
-
- print("시도할 횟수는 몇 회인가요?")
- try_number = try_input()
-
- print("\n실행 결과")
- play_list = print_game_play_result(name_list, try_number)
-
- win_list = check_winner(play_list)
- print("최종 우승자 : {0}".format(', '.join(win_list)))
+ try:
+ print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)")
+ name_list = name_input()
+
+ print("시도할 횟수는 몇 회인가요?")
+ try_number = try_input()
+
+ print("\n실행 결과")
+ play_list = print_game_play_result(name_list, try_number)
+
+ win_list = check_winner(play_list)
+ print(f"최종 우승자 : {', '.join(win_list)}")
+ return 0
+ except ValueError as e:
+ print(f"오류: {e}")
+ return 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.
def main(): | |
""" | |
프로그램의 진입점 함수. | |
여기에서 전체 프로그램 로직을 시작합니다. | |
""" | |
# 프로그램의 메인 로직을 여기에 구현 | |
print("프로그램이 시작되었습니다.") | |
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | |
name_list = name_input() | |
print("시도할 횟수는 몇 회인가요?") | |
try_number = try_input() | |
print("\n실행 결과") | |
play_list = print_game_play_result(name_list, try_number) | |
win_list = check_winner(play_list) | |
print("최종 우승자 : {0}".format(', '.join(win_list))) | |
def main(): | |
""" | |
프로그램의 진입점 함수. | |
여기에서 전체 프로그램 로직을 시작합니다. | |
""" | |
try: | |
print("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분)") | |
name_list = name_input() | |
print("시도할 횟수는 몇 회인가요?") | |
try_number = try_input() | |
print("\n실행 결과") | |
play_list = print_game_play_result(name_list, try_number) | |
win_list = check_winner(play_list) | |
print(f"최종 우승자 : {', '.join(win_list)}") | |
return 0 | |
except ValueError as e: | |
print(f"오류: {e}") | |
return 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: 0
🧹 Nitpick comments (4)
docs/README.md (4)
1-27
: 마크다운 들여쓰기 수정이 필요합니다.마크다운 가독성 향상을 위해 들여쓰기를 수정해 주세요.
## 기능 요구 사항 - - [X] 입력 기능 + - [X] 입력 기능 - - [X] 자동차 이름 입력, 5자 이하의 이름, 쉼표','로 구분분 (ex:pobi,woni,jun) + - [X] 자동차 이름 입력, 5자 이하의 이름, 쉼표','로 구분분 (ex:pobi,woni,jun)예외 처리 예시를 추가하면 좋겠습니다.
입력값 검증에 대한 구체적인 예시가 있으면 더 명확할 것 같습니다.
- [X] 이름 입력 시 예외 사항 - [X] 빈 이름일 경우 - [X] 중복 값이 있는 경우 + 예시: + - 빈 이름: "","," + - 중복 값: "pobi,pobi"🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
3-3: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
4-4: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
7-7: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
8-8: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
9-9: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
10-10: Unordered list indentation
Expected: 4; Actual: 8(MD007, ul-indent)
11-11: Unordered list indentation
Expected: 4; Actual: 8(MD007, ul-indent)
12-12: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
15-15: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
16-16: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
17-17: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
21-21: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
22-22: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
23-23: Unordered list indentation
Expected: 4; Actual: 8(MD007, ul-indent)
24-24: Unordered list indentation
Expected: 4; Actual: 8(MD007, ul-indent)
25-25: Unordered list indentation
Expected: 2; Actual: 4(MD007, ul-indent)
26-26: Unordered list indentation
Expected: 4; Actual: 8(MD007, ul-indent)
28-43
: 함수 문서화를 보완하면 좋겠습니다.각 함수의 파라미터, 반환값, 사용 예시를 추가하면 더 명확할 것 같습니다.
예시 형식:
1. name_input() > 자동차 이름 입력 기능 함수 > > 파라미터: 없음 > 반환값: List[str] - 쉼표로 구분된 자동차 이름 리스트 > > 사용 예시: > 입력: pobi,woni,jun > 반환: ["pobi", "woni", "jun"]
44-48
: 버그 수정 내용을 더 자세히 설명하면 좋겠습니다.버그의 영향과 수정 이유를 추가하면 더 이해하기 쉬울 것 같습니다.
1. is_number() 수정 > str형 검증으로 작동하던 오류를 int형 검증으로 수정 >> ~~str~~int(data) +> +> 수정 이유: +> - str형 검증은 숫자 형태의 문자열도 유효하다고 판단하는 문제가 있었음 +> - 정수 입력만 허용하기 위해 int형 검증으로 변경 +> +> 예시: +> - 수정 전: "123" -> 유효함 (문제) +> - 수정 후: "123" -> ValueError 발생 (의도한 동작)
49-51
: 기능 수정의 이점을 설명하면 좋겠습니다.함수 분리의 목적과 이점을 추가하면 더 이해하기 쉬울 것 같습니다.
1. validate_name() > 이름 입력 값을 검증(이름 길이, null값, 중복) 기능을 validate_input()으로부터 함수 분리 +> +> 분리 이유: +> - 단일 책임 원칙(SRP)을 준수하여 코드 유지보수성 향상 +> - 이름 검증 로직의 재사용성 증가 +> - 테스트 용이성 개선
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
docs/README.md
(1 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
docs/README.md
3-3: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
4-4: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
7-7: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
8-8: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
9-9: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
10-10: Unordered list indentation
Expected: 4; Actual: 8
(MD007, ul-indent)
11-11: Unordered list indentation
Expected: 4; Actual: 8
(MD007, ul-indent)
12-12: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
15-15: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
16-16: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
17-17: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
21-21: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
22-22: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
23-23: Unordered list indentation
Expected: 4; Actual: 8
(MD007, ul-indent)
24-24: Unordered list indentation
Expected: 4; Actual: 8
(MD007, ul-indent)
25-25: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
26-26: Unordered list indentation
Expected: 4; Actual: 8
(MD007, ul-indent)
Summary by CodeRabbit