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 13 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
84 changes: 83 additions & 1 deletion src/racingcar/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,92 @@
import random


THRESHOLD = 4 # 성공 기준 값
MAX_RANDOM_VALUE = 10 # 랜덤 숫자의 최대값


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

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

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L15-L16

Added lines #L15 - L16 were not covered by tests


def validate_name(data):
for i in range(len(data)):
if len(data[i]) > 5:
raise ValueError("이름은 5자 이하만 가능합니다.")
elif len(data[i]) == 0:
raise ValueError("이름은 빈칸일 수 없습니다.")

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

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L24

Added line #L24 was not covered by tests
elif data.count(data[i]) != 1:
raise ValueError("중복되는 이름이 있습니다.")

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

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L26

Added line #L26 was not covered by tests
data[i] = [data[i], 0]


def validate_input(data):
if isinstance(data, str):
is_number(data)
if int(data) <= 0:
raise ValueError("시도할 횟수는 양의 정수이어야 합니다.")

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

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L34

Added line #L34 was not covered by tests
elif isinstance(data, list):
validate_name(data)
return data


def try_input():
print("시도할 횟수는 몇 회인가요?")
try_number = input()
validate_input(try_number)
return int(try_number)


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
return data


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 61 in src/racingcar/main.py

View check run for this annotation

Codecov / codecov/patch

src/racingcar/main.py#L61

Added line #L61 was not covered by tests
return win_list


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]))
print()
return data


def main():
"""
프로그램의 진입점 함수.
여기에서 전체 프로그램 로직을 시작합니다.
"""
# 프로그램의 메인 로직을 여기에 구현
print("프로그램이 시작되었습니다.")
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)))
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. try-except 블록으로 오류를 처리하면 좋겠습니다.
  2. 입력값 처리를 더 견고하게 만들 수 있습니다.
-    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.

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



if __name__ == "__main__":
Expand Down
Loading