본문 바로가기

파이썬으로 로또 1등 도전기

20일차) 전, 전전 회차의 당첨 번호를 제외 수에 추가하기

728x90


안녕하세요, 로또 애호가 여러분! 🌟 오늘은 로또 프로그래밍의 신비로운 세계에 뛰어들어 보겠습니다. 특히, 우리는 지난 두 회차의 당첨 번호를 확인하여 이를 제외 수에 추가하는 기능을 로또 애플리케이션에 추가하는 방법을 알아볼 거예요.

하나씩 살펴볼까요? 🤔

## 시나리오

여러분은 로또를 열심히 플레이하는 팬이라고 상상해 보세요. 다음 추첨을 손꼽아 기다리면서 행운의 숫자를 골라놓았어요. 그런데 지난 두 회차에 나온 숫자를 **제외**할 수 있다면 어떻게 될까요? 더 좋은 기회를 가질 수 있지 않을까요? 🧐

우리의 코드는 바로 이걸 도와주는 역할을 합니다! 그럼 이 기능을 Flask 애플리케이션에서 구현하는 방법을 살펴보겠습니다.

### 1단계: 당첨 번호 가져오기

먼저, 지난 30회의 당첨 번호를 가져와야 합니다. 이때 신뢰할 수 있는 `fetch_winning_numbers()` 함수가 큰 역할을 합니다:

def fetch_winning_numbers():
    latest_draw_no = get_latest_draw_no()  # 최신 회차 번호 가져오기
    winning_numbers_dict = {}  # 회차 번호를 키로 하는 당첨 번호 딕셔너리

    # 최근 30회차의 당첨 번호 가져오기
    for i in range(30):
        draw_no = latest_draw_no - i
        winning_numbers, _ = get_lotto_winning_numbers(draw_no)  # 당첨 번호와 보너스 가져오기

        if winning_numbers:
            winning_numbers_dict[draw_no] = winning_numbers  # 당첨 번호 저장

    return winning_numbers_dict



### 2단계: 제외 수 가져오기

이제 재미있는 부분으로 넘어갑니다! 현재 회차와 로또 규칙에 따라 제외 수를 확인해야 해요. 이를 위해 `get_excluded_numbers_route()` 함수에서 작업을 진행합니다. 여기서 일부 코드를 살펴볼까요?

@app.route('/get_excluded_numbers')
def get_excluded_numbers_route():
    round = int(request.args.get('round'))
    # 로또 규칙 가져오기 및 초기화
    lotto_rules = get_lotto_rules_from_db()  # 로또 규칙 가져오기
    lotto_numbers_list = []
    combined_excluded_numbers = set()  # 유니크한 제외 수를 위한 집합

    # 모든 로또 규칙을 순회
    for rule in lotto_rules:
        # 규칙의 파라미터 추출
        exclude_indices = rule['exclude_indices']
        exclude_bonus = rule['exclude_bonus']
        lotto_round = rule['lotto_round']
        pre_lotto_round = rule['pre_lotto_round']
        
        # 현재 규칙에서 제외 수 가져오기
        excluded_numbers, target_numbers, target_bonus = get_excluded_numbers(
            round, lotto_round, pre_lotto_round, exclude_indices, exclude_bonus
        )

        # 제외 수를 업데이트
        if excluded_numbers is not None:
            combined_excluded_numbers.update(excluded_numbers)

        # 현재 규칙의 번호를 리스트에 추가
        lotto_numbers_list.append({
            "excluded_numbers": excluded_numbers if excluded_numbers is not None else [],
            "target_numbers": target_numbers if target_numbers is not None else [],
            "target_bonus": target_bonus if target_bonus is not None else None
        })



### 3단계: 전, 전전 회차의 연속된 숫자 추가하기

이제 진짜 마법이 시작되는 부분입니다! 우리는 `fetch_winning_numbers()`를 통해 당첨 번호를 가져오고, 이전 두 회차와의 연속된 당첨 번호를 확인합니다.

그 방법은 다음과 같습니다:

winning_numbers = fetch_winning_numbers()
print('winning_numbers : ', winning_numbers)

# 전, 전전 회차와의 연속된 숫자 확인
excluded_from_consecutive = find_consecutive_excluded_numbers(winning_numbers, round)
print('excluded_from_consecutive : ', excluded_from_consecutive)

# 이 연속된 숫자들을 제외 수에 추가
combined_excluded_numbers.update(excluded_from_consecutive)



`find_consecutive_excluded_numbers` 함수는 현재 회차의 당첨 번호를 이전 두 회차의 번호와 비교하여 중복된 번호를 찾아냅니다. 이렇게 찾은 번호는 제외 수에 추가됩니다!

### 마무리

마지막으로, 우리는 결합된 제외 수를 정렬하고, 이를 JSON 형식으로 반환하여 프론트엔드에서 사용할 수 있도록 합니다. 이렇게 정리할 수 있습니다:

# 정렬한 유니크한 제외 수 반환
unique_excluded_numbers = sorted(combined_excluded_numbers)

print('unique_excluded_numbers : ', unique_excluded_numbers)

return jsonify({"lotto_numbers": lotto_numbers_list, "unique_excluded_numbers": unique_excluded_numbers})



## 결론

이렇게 해서 우리는 이전 두 회차의 당첨 번호를 제외 수에 추가하여 사용자들이 더 나은 선택을 할 수 있도록 도와주는 기능을 구현했습니다. 🌈

코딩이 이렇게 재미있을 줄 누가 알았나요? 질문이 있거나 여러분의 생각을 공유하고 싶으시다면 아래 댓글로 남겨 주세요! 로또 플레이를 즐기세요! 🍀💰

728x90