Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[자동차 경주] 원영진 과제 제출합니다. #5

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 62 additions & 1 deletion src/racingcar/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,71 @@
import random


def is_number(Data):
Copy link
Member

Choose a reason for hiding this comment

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

pameter는 소문자로 시작하는 것이 권장됩니다.
Editer의 리팩토링-Rename 기능으로 수정해보시죠.

"""
Data가 숫자인지 확인하는 함수.
숫자가 아니면 ValueError를 발생시킴.
"""
try:
int(Data) # Data가 int 형식인지 확인
except ValueError as e:
raise ValueError("숫자만 입력해주세요.") from e # 숫자가 아닌 값 입력시 예외 처리

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

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L11-L12

Added lines #L11 - L12 were not covered by tests


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
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

입력 검증 로직을 개선해주세요.

현재 구현에서 개선이 필요한 부분들이 있습니다:

  1. 빈 입력이나 빈 이름에 대한 검증이 없습니다
  2. 파이썬스러운 방식으로 개선할 수 있습니다

다음과 같이 수정을 제안합니다:

 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.

Suggested change
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]

Copy link
Member

Choose a reason for hiding this comment

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

빈 이름에 대한 검증이 힘들 것 같네요.



def try_input():
print("시도할 횟수는 몇 회인가요?")
n = input()
Copy link
Member

Choose a reason for hiding this comment

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

코딩테스트가 아닌 경우에는 변수명을 더 명확히 작성해주는 것이 좋습니다.

is_number(n)
return int(n)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

시도 횟수 검증을 강화해주세요.

시도 횟수에 대한 추가 검증이 필요합니다:

  1. 음수나 0 입력 방지
  2. 최대 시도 횟수 제한

다음과 같이 수정을 제안합니다:

 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.

Suggested change
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

Copy link
Member

Choose a reason for hiding this comment

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

시도 횟수에 대한 추가 검증이 있다면 좋을 것 같네요.



def play_1set_of_game(Data):
for i in range(len(Data)):
value = random.randint(0, 10)
if value >= 4:
Copy link
Member

Choose a reason for hiding this comment

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

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

Data[i][1] += 1
return Data
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

상수 정의와 Python 스타일을 개선해주세요.

  1. 매직 넘버를 상수로 정의해주세요
  2. Python 스타일의 반복문을 사용해주세요
  3. 함수 이름을 더 명확하게 해주세요
+# 상수 정의
+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.

Suggested change
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



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])

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

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L44

Added line #L44 was not covered by tests
return win_list


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]))
Copy link
Member

Choose a reason for hiding this comment

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

함수로 바꾸는 게 더 가독성이 좋을 것 같습니다.

print()

win_list = check_winner(name_list)

print("최종 우승자 : {0}".format(', '.join(win_list)))


if __name__ == "__main__":
Expand Down
Loading