-
Notifications
You must be signed in to change notification settings - Fork 5
[로또] 소현우 미션 제출합니다. #1
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
base: main
Are you sure you want to change the base?
Changes from all commits
47504c3
9926aad
80c30cc
2becc69
7d4386e
7a69cdc
33ff896
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# 🎰 Lotto 프로그램 | ||
|
||
## 📜 **Lotto 클래스 기능 정리** | ||
|
||
### 🎲 **1. 로또 번호 처리** | ||
✅ `__init__(self, numbers: List[int])` | ||
- 로또 번호를 입력받아 저장하고 검증합니다. | ||
|
||
✅ `_validate(numbers: List[int])` | ||
- 로또 번호가 **6개인지, 중복이 없는지, 1~45 범위 내에 있는지** 검증합니다. | ||
|
||
--- | ||
|
||
### 💰 **2. 로또 구입 관련** | ||
✅ `get_lotto_count()` | ||
- 사용자에게 **로또 구입 금액을 입력받고** 구입할 수 있는 개수를 계산합니다. | ||
- **1,000원 단위로만 구입 가능**합니다. | ||
|
||
✅ `_validate_amount(amount)` | ||
- 입력된 금액이 **숫자인지, 1,000원 이상인지, 1,000원 단위인지** 확인합니다. | ||
|
||
--- | ||
|
||
### 🎟️ **3. 로또 번호 생성** | ||
✅ `generate_random_lotto()` | ||
- **1~45 사이의 랜덤한 6개의 숫자**를 생성하여 로또 번호를 만듭니다. | ||
|
||
✅ `generate_lottos(count: int)` | ||
- **사용자가 구입한 개수만큼** 로또 번호를 자동 생성합니다. | ||
|
||
--- | ||
|
||
### 🎯 **4. 당첨 번호 입력** | ||
✅ `get_winning_numbers()` | ||
- **사용자로부터 당첨 번호와 보너스 번호를 입력받습니다.** | ||
- 입력된 번호가 **유효한지 검증한 후 반환합니다.** | ||
|
||
✅ `_get_valid_numbers(prompt, count)` | ||
- **사용자가 입력한 당첨 번호가 6개인지, 유효한 범위(1~45)인지 확인**합니다. | ||
|
||
✅ `_validate_numbers(numbers, count)` | ||
- 입력된 숫자가 **개수 조건(6개) 및 범위(1~45)를 만족하는지 검증**합니다. | ||
|
||
✅ `_get_valid_bonus(prompt, numbers)` | ||
- **보너스 번호를 입력받아 유효성 검증**을 수행합니다. | ||
|
||
✅ `_is_valid_bonus(bonus, numbers)` | ||
- 보너스 번호가 **1~45 사이이며, 당첨 번호와 중복되지 않는지** 확인합니다. | ||
|
||
--- | ||
|
||
### 🏆 **5. 당첨 결과 비교** | ||
✅ `check_results(purchased_lottos, winning_numbers, bonus_number)` | ||
- **구입한 로또 번호와 당첨 번호를 비교**하여 당첨 등수를 결정합니다. | ||
|
||
✅ `_count_matches(lotto_numbers, winning_numbers, bonus_number)` | ||
- 각 로또 번호가 **당첨 번호와 몇 개 일치하는지, 보너스 번호가 포함되어 있는지** 확인합니다. | ||
|
||
✅ `_determine_prize_key(matched_count, has_bonus)` | ||
- 일치 개수 및 보너스 번호 여부를 바탕으로 **당첨 등수를 판별**합니다. | ||
|
||
--- | ||
|
||
### 📊 **6. 당첨 결과 출력** | ||
✅ `print_results(results, total_cost)` | ||
- **각 당첨 등수별 개수를 출력**합니다. | ||
- 총 당첨 금액과 **수익률(%)을 계산하여 출력**합니다. |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,4 +2,3 @@ | |
pythonpath = src | ||
markers = | ||
custom_name: 테스트 설명을 위한 커스텀 마커 | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,5 @@ | ||
# src/lotto/__init__.py | ||
"""로또 패키지 초기화 파일""" | ||
|
||
# 📌 이 패키지는 로또 관련 기능을 제공하는 모듈입니다. | ||
# 외부에서 `from lotto import Lotto`와 같은 방식으로 사용할 수 있도록 | ||
# 필요한 모듈을 여기에 등록하세요. | ||
# | ||
# ✅ 새로운 모듈을 추가할 경우: | ||
# - `from .[모듈명] import [클래스/함수]` 형식으로 추가하세요. | ||
# - 필요한 경우 `__all__`에 추가하여 패키지 외부에서 명확하게 사용할 수 있도록 정의하세요. | ||
# - `flake8`의 F401 경고(`imported but unused`)가 발생하는 경우, `__all__`을 활용해 해결하세요. | ||
from .lotto import Lotto | ||
|
||
from .lotto import Lotto # 🎲 로또 번호 생성 및 검증을 위한 클래스 | ||
|
||
# 패키지 외부에서 `from lotto import *` 사용 시 제공할 모듈을 명시적으로 정의합니다. | ||
__all__ = ["Lotto"] | ||
|
||
# 💡 예시: 새로운 모듈을 추가할 때 | ||
# from .other_module import OtherClass # 🆕 예: 새로운 클래스 추가 시 | ||
# __all__.append("OtherClass") # `__all__`에 추가하여 외부에서 접근 가능하게 함. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,214 @@ | ||
from typing import List | ||
"""lotto.py: 로또 번호 생성 및 당첨 결과를 처리하는 모듈""" | ||
|
||
import random | ||
from enum import Enum | ||
|
||
|
||
class Prize(Enum): | ||
"""당첨 등수를 Enum으로 정의""" | ||
THREE_MATCH = 3 | ||
FOUR_MATCH = 4 | ||
FIVE_MATCH = 5 | ||
FIVE_MATCH_BONUS = "5_bonus" | ||
SIX_MATCH = 6 | ||
|
||
|
||
class Lotto: | ||
def __init__(self, numbers: List[int]): | ||
"""로또 번호 및 당첨 결과를 처리하는 클래스""" | ||
|
||
def __init__(self, numbers: list[int]): | ||
self._validate(numbers) | ||
self._numbers = numbers | ||
|
||
def _validate(self, numbers: List[int]): | ||
@property | ||
def numbers(self): | ||
"""로또 번호를 반환하는 getter 메서드""" | ||
return self._numbers | ||
|
||
def _validate(self, numbers: list[int]): | ||
"""로또 번호 검증: 개수, 중복, 범위""" | ||
if len(numbers) != 6: | ||
raise ValueError | ||
raise ValueError("로또 번호는 정확히 6개여야 합니다.") | ||
if len(set(numbers)) != 6: | ||
raise ValueError("로또 번호에 중복이 있어서는 안 됩니다.") | ||
if not all(1 <= num <= 45 for num in numbers): | ||
raise ValueError("로또 번호는 1부터 45 사이여야 합니다.") | ||
|
||
@staticmethod | ||
def get_lotto_count(): | ||
"""로또 구입 금액 입력 및 예외 처리""" | ||
try: | ||
amount = input("로또 구입 금액을 입력하세요: ") | ||
Lotto._validate_amount(amount) | ||
|
||
amount = int(amount) | ||
lotto_count = amount // 1000 | ||
print(f"{lotto_count}개의 로또를 구입합니다.") | ||
return lotto_count | ||
|
||
except ValueError as e: | ||
print(e) | ||
raise | ||
Comment on lines
+38
to
+51
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. UI 로직을 별도의 클래스로 분리해야 합니다. 현재 Lotto 클래스에 비즈니스 로직과 UI 로직이 혼재되어 있습니다. 단일 책임 원칙(SRP)을 준수하고 관심사를 분리하기 위해 UI 관련 로직을 별도의 클래스로 분리해야 합니다. 다음과 같은 구조로 리팩토링하는 것을 제안합니다:
class LottoUI:
@staticmethod
def get_purchase_amount():
return input("로또 구입 금액을 입력하세요: ")
@staticmethod
def print_purchase_count(count):
print(f"{count}개의 로또를 구입합니다.")
# 나머지 UI 관련 메서드들...
class Lotto:
@staticmethod
def validate_amount(amount):
# 검증 로직만 포함
pass
@staticmethod
def get_lotto_count(amount):
# 계산 로직만 포함
return amount // 1000 Also applies to: 81-92, 102-109, 111-117, 175-196 |
||
|
||
@staticmethod | ||
def _validate_amount(amount): | ||
"""로또 금액 검증""" | ||
if not amount.isdigit(): | ||
raise ValueError("[ERROR] 숫자를 입력하세요.") | ||
|
||
amount = int(amount) | ||
if amount < 1000 or amount % 1000 != 0: | ||
raise ValueError("[ERROR] 최소 1,000원 이상, 1,000원 단위로 입력해야 합니다.") | ||
|
||
@staticmethod | ||
def generate_random_lotto(): | ||
"""무작위 로또 번호 생성""" | ||
return Lotto(sorted(random.sample(range(1, 46), 6))) | ||
|
||
@staticmethod | ||
def generate_lottos(count: int): | ||
"""구입한 로또 개수만큼 번호 생성""" | ||
return [Lotto.generate_random_lotto() for _ in range(count)] | ||
|
||
@staticmethod | ||
def get_winning_numbers(): | ||
"""당첨 번호 및 보너스 번호 입력""" | ||
numbers = Lotto._get_valid_numbers("당첨 번호를 입력해 주세요: ", 6) | ||
bonus = Lotto._get_valid_bonus("보너스 번호 1개를 입력하세요: ", numbers) | ||
return numbers, bonus | ||
|
||
@staticmethod | ||
def _get_valid_numbers(prompt, count): | ||
"""유효한 번호 입력 받기""" | ||
while True: | ||
try: | ||
numbers = list( | ||
map(int, input(prompt).replace(',', ' ').split()) | ||
) | ||
Lotto._validate_numbers(numbers, count) | ||
return numbers | ||
except ValueError as e: | ||
print(e) | ||
|
||
@staticmethod | ||
def _validate_numbers(numbers, count): | ||
"""입력된 숫자 검증""" | ||
if len(numbers) != count or len(set(numbers)) != count: | ||
raise ValueError(f"[ERROR] {count}개의 숫자를 입력해야 하며, 중복이 없어야 합니다.") | ||
if not all(1 <= num <= 45 for num in numbers): | ||
raise ValueError("[ERROR] 숫자는 1부터 45 사이여야 합니다.") | ||
|
||
@staticmethod | ||
def _get_valid_bonus(prompt, numbers): | ||
"""보너스 번호 입력 받기""" | ||
while True: | ||
bonus = Lotto._safe_input_bonus(prompt) | ||
if Lotto._is_valid_bonus(bonus, numbers): | ||
return bonus | ||
print("[ERROR] 올바른 보너스 번호를 입력하세요.") | ||
|
||
@staticmethod | ||
def _safe_input_bonus(prompt): | ||
"""보너스 번호 안전 입력""" | ||
try: | ||
return int(input(prompt)) | ||
except ValueError: | ||
return -1 # 잘못된 값 반환 (검증에서 걸러짐) | ||
|
||
@staticmethod | ||
def _is_valid_bonus(bonus, numbers): | ||
"""보너스 번호 검증""" | ||
if bonus in numbers or not 1 <= bonus <= 45: | ||
return False | ||
return True | ||
|
||
@staticmethod | ||
def check_results(purchased_lottos, winning_numbers, bonus_number): | ||
"""구입한 로또 번호와 당첨 번호 비교""" | ||
results = { | ||
Prize.THREE_MATCH: 0, | ||
Prize.FOUR_MATCH: 0, | ||
Prize.FIVE_MATCH: 0, | ||
Prize.FIVE_MATCH_BONUS: 0, | ||
Prize.SIX_MATCH: 0, | ||
} | ||
|
||
for lotto in purchased_lottos: | ||
matched_count, has_bonus = Lotto._count_matches( | ||
lotto.numbers, winning_numbers, bonus_number | ||
) | ||
|
||
Lotto._update_results(results, matched_count, has_bonus) | ||
|
||
return results | ||
|
||
@staticmethod | ||
def _update_results(results, matched_count, has_bonus): | ||
"""당첨 결과 딕셔너리를 업데이트""" | ||
key = Lotto._determine_prize_key(matched_count, has_bonus) | ||
if key: | ||
results[key] += 1 | ||
|
||
@staticmethod | ||
def _count_matches(lotto_numbers, winning_numbers, bonus_number): | ||
"""로또 번호와 당첨 번호 비교하여 일치 개수와 보너스 여부 반환""" | ||
matched_count = len(set(lotto_numbers) & set(winning_numbers)) | ||
has_bonus = bonus_number in lotto_numbers | ||
return matched_count, has_bonus | ||
|
||
@staticmethod | ||
def _determine_prize_key(matched_count, has_bonus): | ||
"""당첨 등수 판별""" | ||
if matched_count == 5 and has_bonus: | ||
return Prize.FIVE_MATCH_BONUS | ||
if matched_count == 6: | ||
return Prize.SIX_MATCH | ||
if matched_count == 5: | ||
return Prize.FIVE_MATCH | ||
if matched_count == 4: | ||
return Prize.FOUR_MATCH | ||
if matched_count == 3: | ||
return Prize.THREE_MATCH | ||
return None | ||
|
||
@staticmethod | ||
def print_results(results, total_cost): | ||
"""당첨 통계를 출력하고 수익률을 계산하여 표시""" | ||
print("\n당첨 통계") | ||
print("---") | ||
Lotto.print_winning_statistics(results) | ||
|
||
total_prize = Lotto.calculate_total_prize(results) | ||
profit_ratio = Lotto.calculate_profit_ratio(total_prize, total_cost) | ||
|
||
print(f"총 수익률은 {profit_ratio:.1f}%입니다.") | ||
|
||
@staticmethod | ||
def print_winning_statistics(results): | ||
"""당첨 개수를 출력""" | ||
print( | ||
f"3개 일치 (5,000원) - {results[Prize.THREE_MATCH]}개\n" | ||
f"4개 일치 (50,000원) - {results[Prize.FOUR_MATCH]}개\n" | ||
f"5개 일치 (1,500,000원) - {results[Prize.FIVE_MATCH]}개\n" | ||
"5개 일치, 보너스 볼 일치 (30,000,000원) - " | ||
f"{results[Prize.FIVE_MATCH_BONUS]}개\n" | ||
f"6개 일치 (2,000,000,000원) - {results[Prize.SIX_MATCH]}개" | ||
) | ||
|
||
@staticmethod | ||
def calculate_total_prize(results): | ||
"""총 당첨 금액 계산""" | ||
return ( | ||
results[Prize.THREE_MATCH] * 5000 | ||
+ results[Prize.FOUR_MATCH] * 50000 | ||
+ results[Prize.FIVE_MATCH] * 1500000 | ||
+ results[Prize.FIVE_MATCH_BONUS] * 30000000 | ||
+ results[Prize.SIX_MATCH] * 2000000000 | ||
) | ||
Comment on lines
+187
to
+207
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 상금 계산 로직을 Prize Enum과 통합하면 좋겠습니다. 상금 금액이 여러 곳에 하드코딩되어 있어 유지보수가 어려울 수 있습니다. Prize Enum에서 상금 정보를 가져오도록 수정하면 좋겠습니다. Prize Enum 리팩토링 후 다음과 같이 수정할 수 있습니다: @staticmethod
def calculate_total_prize(results):
"""총 당첨 금액 계산"""
return sum(
results[prize] * prize.prize_amount
for prize in Prize
)
@staticmethod
def print_winning_statistics(results):
"""당첨 개수를 출력"""
for prize in Prize:
print(f"{prize.match_count}개 일치 ({prize.prize_amount:,}원) - {results[prize]}개") |
||
|
||
# TODO: 추가 기능 구현 | ||
@staticmethod | ||
def calculate_profit_ratio(total_prize, total_cost): | ||
"""수익률 계산""" | ||
if total_cost > 0: | ||
return (total_prize / total_cost) * 100 | ||
return 0 | ||
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,35 @@ | ||
"""main.py: 로또 프로그램의 실행을 담당하는 메인 스크립트""" | ||
|
||
from lotto import Lotto | ||
|
||
|
||
def main(): | ||
# TODO: 프로그램 구현 | ||
pass | ||
"""로또 프로그램 실행 함수""" | ||
# 1. 로또 구입 개수 입력 | ||
lotto_count = Lotto.get_lotto_count() | ||
|
||
# 2. 로또 번호 생성 | ||
purchased_lottos = Lotto.generate_lottos(lotto_count) | ||
|
||
# 📌 요구된 형식으로 출력 | ||
print(f"\n{lotto_count}개를 구매했습니다.") | ||
for lotto in purchased_lottos: | ||
print(f"{lotto.numbers}") # ✅ 리스트 형태를 그대로 출력 | ||
|
||
# 3. 당첨 번호 및 보너스 번호 입력 | ||
winning_numbers, bonus_number = Lotto.get_winning_numbers() | ||
|
||
# 4. 당첨 결과 확인 | ||
results = Lotto.check_results( | ||
purchased_lottos, | ||
winning_numbers, | ||
bonus_number | ||
) | ||
|
||
# 5. 당첨 통계 및 수익률 출력 | ||
total_cost = lotto_count * 1000 # 총 구입 금액 | ||
Lotto.print_results(results, total_cost) | ||
|
||
|
||
if __name__ == "__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.
파일 끝에 개행 문자를 추가해주세요.
YAML 파일의 마지막 줄에는 개행 문자가 있어야 합니다. 이는 텍스트 파일의 표준 요구사항입니다.
파일의 마지막에 빈 줄을 추가해주세요.
🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 46-46: no new line character at the end of file
(new-line-at-end-of-file)