-
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
Open
so528
wants to merge
7
commits into
swthewhite-lab:main
Choose a base branch
from
so528:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
47504c3
[로또 게임]소현우 과제 제출합니다.
so528 9926aad
update code
so528 80c30cc
Merge branch 'main' into main
swthewhite 2becc69
refactor: Improve code structure and fix pylint warnings
so528 7d4386e
Merge branch 'main' into main
swthewhite 7a69cdc
refactor: improve code structure and fix pylint warnings2
so528 33ff896
refactor: improve code structure and fix pylint warnings2
so528 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)` | ||
| - **각 당첨 등수별 개수를 출력**합니다. | ||
| - 총 당첨 금액과 **수익률(%)을 계산하여 출력**합니다. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,4 @@ | ||
| [pytest] | ||
| pythonpath = src | ||
| markers = | ||
| custom_name: 사용자 지정 마크 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| from .lotto import Lotto |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,188 @@ | ||
| from typing import List | ||
| 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]): | ||
| 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 | ||
|
|
||
| @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 | ||
| ) | ||
| key = Lotto._determine_prize_key(matched_count, has_bonus) | ||
| if key: | ||
| results[key] += 1 | ||
|
|
||
| return results | ||
|
|
||
| @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("---") | ||
| 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]}개" | ||
| ) | ||
|
|
||
| total_prize = ( | ||
| 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 | ||
| ) | ||
| profit_ratio = 0 | ||
| if total_cost > 0: | ||
| profit_ratio = (total_prize / total_cost) * 100 | ||
|
|
||
| # TODO: 추가 기능 구현 | ||
| print(f"총 수익률은 {profit_ratio:.1f}%입니다.") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,32 @@ | ||
| 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
UI 로직을 별도의 클래스로 분리해야 합니다.
현재 Lotto 클래스에 비즈니스 로직과 UI 로직이 혼재되어 있습니다. 단일 책임 원칙(SRP)을 준수하고 관심사를 분리하기 위해 UI 관련 로직을 별도의 클래스로 분리해야 합니다.
다음과 같은 구조로 리팩토링하는 것을 제안합니다:
LottoUI클래스 생성:Also applies to: 81-92, 102-109, 111-117, 175-196