import random

# 변수 설정
n_tickets = 500  # 한 번에 구매할 복권 장수 (n번 복권 구매)
lottery_price = 30000  # 복권 한 장의 가격
num_simulations = 1000  # 전체 시뮬레이션 반복 횟수 (m번 반복)

# 등수별 확률 및 상금 데이터
lottery_data = [
    {"rank": 1, "probability": 0.000448, "prize": 20000000},
    {"rank": 2, "probability": 0.007921, "prize": 500000},
    {"rank": 3, "probability": 0.054456, "prize": 150000},
    {"rank": 4, "probability": 0.186706, "prize": 50000},
    {"rank": 5, "probability": 0.337344, "prize": 20000},
    {"rank": 6, "probability": 0.305077, "prize": 10000},
    {"rank": 7, "probability": 0.108048, "prize": 0},
]

# 당첨 확률을 누적 확률로 변환
cumulative_probabilities = []
current_probability = 0
for item in lottery_data:
    current_probability += item["probability"]
    cumulative_probabilities.append(current_probability)

# 복권 1장의 결과를 시뮬레이션
def simulate_single_ticket():
    rnd = random.random()  # 0~1 사이의 난수 생성
    for i, cum_prob in enumerate(cumulative_probabilities):
        if rnd <= cum_prob:
            return lottery_data[i]["prize"]
    return 0  # 기본 값

# n번 복권 구매의 결과를 시뮬레이션
def simulate_n_tickets(num_tickets):
    total_prize = sum(simulate_single_ticket() for _ in range(num_tickets))
    return total_prize

# m번 반복해서 복권 시뮬레이션 실행
def simulate_lottery(num_tickets, ticket_price, simulations):
    total_cost = num_tickets * ticket_price
    profit_count = 0
    total_profit = 0  # 이득 총합
    total_loss = 0    # 손해 총합
    total_final_amount = 0  # 최종 금액 총합

    # 시뮬레이션 실행
    for i in range(simulations):
        # n번 복권 구매 후 결과 계산
        total_prize = simulate_n_tickets(num_tickets)
        net_result = total_prize - total_cost  # 이득 또는 손해

        # 최종 금액 계산
        total_final_amount += net_result

        if net_result > 0:
            profit_count += 1
            total_profit += net_result
        else:
            total_loss += abs(net_result)

    # 확률 및 평균 계산
    profit_probability = (profit_count / simulations) * 100  # 이득 볼 확률 (%)
    avg_profit = total_profit / profit_count if profit_count > 0 else 0
    avg_loss = total_loss / (simulations - profit_count) if profit_count < simulations else 0
    avg_final_amount = total_final_amount / simulations  # 최종 금액 평균

    return profit_probability, avg_profit, avg_loss, avg_final_amount

# 계산
profit_probability, avg_profit, avg_loss, avg_final_amount = simulate_lottery(n_tickets, lottery_price, num_simulations)

# 결과 출력
total_cost = n_tickets * lottery_price

# 최종 금액 평균 부호 표시
if avg_final_amount >= 0:
    final_amount_str = f"+{avg_final_amount:,.0f}원"  # 양수일 때 + 표시
else:
    final_amount_str = f"{avg_final_amount:,.0f}원"  # 음수일 때 기본 - 표시

print()
print(f"{n_tickets:,.0f} 장을 구매했을 때:")
print(f"{num_simulations:,.0f} 번 시뮬레이션:")
print()
print(f"- 복권 구매 비용: {total_cost:,.0f}원")
print()
print(f"- 전체적으로 이득을 볼 확률: {profit_probability:.4f}%")
print()
print(f"- 이득을 본 경우 평균 이득: {avg_profit:,.0f}원")
print(f"- 손해를 본 경우 평균 손해: {avg_loss:,.0f}원")
print()
print(f"- 최종 금액 평균: {final_amount_str}")
print()

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: