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

[로또] 김성규 미션 제출합니다. #4

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion .github/workflows/check-no-external-libs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
module_path = os.path.join('src', module_name.replace('.', '/') + '.py')
module_dir = os.path.join('src', module_name.replace('.', '/'))
return os.path.exists(module_path) or os.path.isdir(module_dir)

def check_imports(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
tree = ast.parse(f.read(), filename=file_path)
Expand Down
24 changes: 24 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# 기능 목록 정리
1. 입력 처리
- 로또 구입 금액 입력 (1000원 단위인지 확인)
- 당첨 번호 입력 (1~45 범위, 6개 중복 없음)
- 보너스 번호 입력 (1~45 범위, 당첨 번호와 중복 없음)

2. 로또 발행
- 입력한 금액만큼 로또 자동 생성 (중복 없는 6개 번호)
- 로또 번호는 오름차순 정렬

3. 당첨 결과 계산
- 각 로또 번호와 당첨 번호 비교
- 보너스 번호 포함 여부 확인
- 등수 판별 (1등~5등)
- 당첨 내역 카운트

4. 출력 처리
- 구매한 로또 출력
- 당첨 내역 출력
- 총 수익률 계산 및 출력 (소수점 둘째 자리 반올림)

5.예외 처리
- 잘못된 입력 ([ERROR] 메시지 출력 후 재입력)
- ValueError 발생 시 처리
1 change: 0 additions & 1 deletion pytest.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@
pythonpath = src
markers =
custom_name: 테스트 설명을 위한 커스텀 마커

47 changes: 41 additions & 6 deletions src/lotto/lotto.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,47 @@
from typing import List
from enum import Enum
import random


class Lotto:
def __init__(self, numbers: List[int]):
def __init__(self, numbers: list[int]):
self._validate(numbers)
self._numbers = numbers
self._numbers = sorted(numbers)

def _validate(self, numbers: List[int]):
def _validate(self, numbers: list[int]):
if len(numbers) != 6:
raise ValueError
raise ValueError("로또 번호의 개수가 6개가 넘어가면 예외가 발생한다.")
if len(set(numbers)) < 6:
raise ValueError("로또 번호에 중복된 숫자가 있으면 예외가 발생한다.")
if max(numbers) > 45 or min(numbers) < 1:
raise ValueError("로또 번호의 숫자 범위는 1~45까지입니다.")

Check warning on line 16 in src/lotto/lotto.py

View check run for this annotation

Codecov / codecov/patch

src/lotto/lotto.py#L16

Added line #L16 was not covered by tests

@classmethod
def generate_num(clss):
return clss(random.sample(range(1, 46), 6))

def get_numbers(self):
return self._numbers

def __str__(self):
return str(self._numbers)


class Rank(Enum):
FIFTH = (3, False, 5_000)
FOURTH = (4, False, 50_000)
THIRD = (5, False, 1_500_000)
SECOND = (5, True, 30_000_000)
FIRST = (6, False, 2_000_000_000)
NONE = (0, False, 0)

def __init__(self, match_cnt, bonus_match, prize):
self.match_cnt = match_cnt
self.bonus_match = bonus_match
self.prize = prize

# TODO: 추가 기능 구현
@classmethod
def get_rank(clss, match_cnt, bonus):
for rank in clss:
if rank.match_cnt == match_cnt and rank.bonus_match == bonus:
return rank
return clss.NONE
94 changes: 92 additions & 2 deletions src/lotto/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,96 @@
from .lotto import Rank, Lotto

def check_amount(input_amount):
if not input_amount.isdigit():
raise ValueError("[ERROR] 숫자를 입력해 주세요.")
if int(input_amount) % 1000 != 0:
raise ValueError("구입 금액은 1,000원으로 나누어 떨어져야 합니다.")

Check warning on line 7 in src/lotto/main.py

View check run for this annotation

Codecov / codecov/patch

src/lotto/main.py#L7

Added line #L7 was not covered by tests
if int(input_amount) < 1000:
raise ValueError("구입 금액은 1,000원 이상이어야 합니다.")

Check warning on line 9 in src/lotto/main.py

View check run for this annotation

Codecov / codecov/patch

src/lotto/main.py#L9

Added line #L9 was not covered by tests
return int(input_amount) // 1000

def prompt_purchase_amount():
while True:
try:
print("구입금액을 입력해 주세요.")
amount = input()
return check_amount(amount)
except ValueError as error:
print(f"[ERROR] {error}")
raise

Comment on lines +12 to +21
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

[입력이 유효하지 않을 때 반복 구조가 중단됩니다]
이 부분에서 ValueError가 발생하면 raise로 인해 while True 루프를 빠져나갑니다. 계속 입력을 받으려면 raise 대신 사용자에게 재입력을 유도하는 방식(continue)을 고려해 보세요.

-except ValueError as error:
-    print(f"[ERROR] {error}")
-    raise
+except ValueError as error:
+    print(f"[ERROR] {error}")
+    continue
📝 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 prompt_purchase_amount():
while True:
try:
print("구입금액을 입력해 주세요.")
amount = input()
return check_amount(amount)
except ValueError as error:
print(f"[ERROR] {error}")
raise
def prompt_purchase_amount():
while True:
try:
print("구입금액을 입력해 주세요.")
amount = input()
return check_amount(amount)
except ValueError as error:
print(f"[ERROR] {error}")
continue
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 12-12: Expected 2 blank lines, found 1

def print_lotto_tickets(tickets):
print(f"\n{len(tickets)}개를 구매했습니다.")
for ticket in tickets:
print(ticket)

def prompt_winning_numbers():
while True:
print("\n당첨 번호를 입력해 주세요.")
try:
winning_numbers = list(map(int, input().split(",")))
return Lotto(winning_numbers).get_numbers()
except ValueError as error:
print(f"[ERROR] {error}")

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

View check run for this annotation

Codecov / codecov/patch

src/lotto/main.py#L33-L34

Added lines #L33 - L34 were not covered by tests

def check_bonus_number(bonus_num, winning_numbers):
if not bonus_num.isdigit():
raise ValueError("숫자를 입력해 주세요.")

Check warning on line 38 in src/lotto/main.py

View check run for this annotation

Codecov / codecov/patch

src/lotto/main.py#L38

Added line #L38 was not covered by tests
if int(bonus_num) in winning_numbers:
raise ValueError("보너스 숫자와 입력한 당첨 번호는 중복되지 않아야 합니다.")

Check warning on line 40 in src/lotto/main.py

View check run for this annotation

Codecov / codecov/patch

src/lotto/main.py#L40

Added line #L40 was not covered by tests
if int(bonus_num) > 45 or int(bonus_num) < 1:
raise ValueError("로또 번호의 숫자 범위는 1~45까지입니다.")

Check warning on line 42 in src/lotto/main.py

View check run for this annotation

Codecov / codecov/patch

src/lotto/main.py#L42

Added line #L42 was not covered by tests
return int(bonus_num)

def prompt_bonus_number(winning_numbers):
while True:
try:
bonus_num = input("\n보너스 번호를 입력해 주세요.\n")
return check_bonus_number(bonus_num, winning_numbers)
except ValueError as error:
print(f"[ERROR] {error}")

Check warning on line 51 in src/lotto/main.py

View check run for this annotation

Codecov / codecov/patch

src/lotto/main.py#L50-L51

Added lines #L50 - L51 were not covered by tests

def evaluate_tickets(tickets, winning_numbers, bonus_num):
results = {rank: 0 for rank in Rank}
total_prize = 0

for ticket in tickets:
ticket_numbers = ticket.get_numbers()
match_count = len(set(winning_numbers) & set(ticket_numbers))
bonus = bonus_num in ticket_numbers

rank = Rank.get_rank(match_count, bonus)
results[rank] += 1
total_prize += rank.prize

return results, total_prize

def print_results(results, total_prize, amount):
profit_percentage = round((total_prize / (amount * 1000)) * 100, 2)

print("\n당첨 통계")
print("---")
for rank in Rank:
if rank == Rank.SECOND:
print(f"{rank.match_cnt}개 일치, 보너스 볼 일치 ({rank.prize:,}원) - "
f"{results[rank]}개")

if rank != Rank.NONE and rank != Rank.SECOND:
print(f"{rank.match_cnt}개 일치 ({rank.prize:,}원) - "
f"{results[rank]}개")

print(f"총 수익률은 {profit_percentage}%입니다.")

def main():
# TODO: 프로그램 구현
pass
amount = prompt_purchase_amount()
tickets = [Lotto.generate_num() for _ in range(amount)]
print_lotto_tickets(tickets)

winning_numbers = prompt_winning_numbers()
bonus_num = prompt_bonus_number(winning_numbers)

results, total_prize = evaluate_tickets(tickets, winning_numbers, bonus_num)
print_results(results, total_prize, amount)

if __name__ == "__main__":
main()
Loading