Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

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

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
43 changes: 36 additions & 7 deletions src/racingcar/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,41 @@
def main():
"""
프로그램의 진입점 함수.
여기에서 전체 프로그램 로직을 시작합니다.
"""
# 프로그램의 메인 로직을 여기에 구현
print("프로그램이 시작되었습니다.")
import random
car_names = input("경주할 자동차 이름을 입력하세요.(이름은 쉼표로 구분): ").split(",")
car_names = list(set(name.strip() for name in car_names if name.strip()))
car_dict = {}

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

Choose a reason for hiding this comment

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

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

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

car_dict[name] = 0

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

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

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

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

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

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

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

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

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


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:
carPos[name] += 1

for name in carPos:
print(f"{name} : {'-' * carPos[name] if carPos[name] > 0 else ' '}")
print() # 줄바꿈 추가

print() # 최종 출력과 구분을 위해 개행 추가
maxPos = max(carPos.values())
winners = [name for name, pos in carPos.items() if pos == maxPos]

print(f"최종 우승자 : {', '.join(winners)}")

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

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

Choose a reason for hiding this comment

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

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

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


Expand Down