import random

# 변수 설정
n_tickets = 1000  # 구매할 복권 장수
lottery_price = 30000  # 복권 한 장의 가격
num_simulations = 1000  # 시뮬레이션 반복 횟수

# 등수별 확률 및 상금 데이터
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

# 시뮬레이션 실행
def simulate_lottery(num_tickets, ticket_price, simulations):
    total_cost = num_tickets * ticket_price
    profit_count = 0
    total_profit = 0  # 이득 총합
    total_loss = 0    # 손해 총합

    for _ in range(simulations):
        total_prize = simulate_n_tickets(num_tickets)
        net_result = total_prize - total_cost  # 이득 또는 손해

        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

    return profit_probability, avg_profit, avg_loss

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

# 결과 출력
total_cost = n_tickets * lottery_price

if avg_profit > 0:
    final_amount = total_cost + avg_profit  # 이득을 본 경우
else:
    final_amount = total_cost - avg_loss   # 손해를 본 경우

print(f"{n_tickets}장을 구매했을 때:")
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:,.0f}원")

Embed on website

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