import random
from pprint import pprint
items = ["애플 비전 프로", "애플 와치", "Mac M2 pro", "에어팟 pro2", "킨더부에노", "아이스아메리카노", "닥터유", "꽝~! 메롱 약오르지"]
weights = [0.0001, 0.0005, 0.030, 0.040, 0.24, 0.19, 0.19, 0.34]
def gacha_pull(items, weights):
return random.choices(items, weights=weights, k=1)[0]
reward_dict = {item: 0 for item in items}
NUM_BATCHES = 3000000
for i in range(NUM_BATCHES):
results = gacha_pull(items, weights)
reward_dict[results] +=1
pprint(reward_dict)
print("\n==============================\n")
for k, v in reward_dict.items():
print(f"{k} 당첨 확률 : {v / NUM_BATCHES:.5f}")
결과
{'Mac M2 pro': 86974,
'꽝~! 메롱 약오르지': 990898,
'닥터유': 553107,
'아이스아메리카노': 551886,
'애플 비전 프로': 250,
'애플 와치': 1412,
'에어팟 pro2': 116842,
'킨더부에노': 698631}
==============================
애플 비전 프로 당첨 확률 : 0.00008
애플 와치 당첨 확률 : 0.00047
Mac M2 pro 당첨 확률 : 0.02899
에어팟 pro2 당첨 확률 : 0.03895
킨더부에노 당첨 확률 : 0.23288
아이스아메리카노 당첨 확률 : 0.18396
닥터유 당첨 확률 : 0.18437
꽝~! 메롱 약오르지 당첨 확률 : 0.33030
당첨 수 제한
import random
from pprint import pprint
items = ["애플 비전 프로", "애플 와치", "Mac M2 pro", "에어팟 pro2", "킨더부에노", "아이스아메리카노", "닥터유", "꽝~! 메롱 약오르지"]
weights = [0.0001, 0.0005, 0.030, 0.040, 0.24, 0.19, 0.19, 0.34]
limit_dict = {
"애플 비전 프로": 20,
"Mac M2 pro": 50
}
def gacha_pull_with_limit(items, weights, limit_dict):
selected = random.choices(items, weights=weights, k=1)[0]
if selected in limit_dict:
limit_dict[selected] -= 1
if limit_dict[selected] == 0:
idx = items.index(selected)
weights[idx] = 0
return selected
reward_dict = {item: 0 for item in items}
NUM_BATCHES = 3000000
for i in range(NUM_BATCHES):
results = gacha_pull_with_limit(items, weights, limit_dict)
reward_dict[results] += 1
pprint(reward_dict)
print("\n==================================\n")
pprint({k: f"{v / NUM_BATCHES:.5f}" for k, v in reward_dict.items()})
결과
{'Mac M2 pro': 50,
'꽝~! 메롱 약오르지': 1020076,
'닥터유': 569162,
'아이스아메리카노': 569832,
'애플 비전 프로': 20,
'애플 와치': 1510,
'에어팟 pro2': 119489,
'킨더부에노': 719861}
==================================
{'Mac M2 pro': '0.00002',
'꽝~! 메롱 약오르지': '0.34003',
'닥터유': '0.18972',
'아이스아메리카노': '0.18994',
'애플 비전 프로': '0.00001',
'애플 와치': '0.00050',
'에어팟 pro2': '0.03983',
'킨더부에노': '0.23995'}
Django
from django.db import models
class Item(models.Model):
price = models.IntegerField()
weight = models.FloatField()
limit = models.IntegerField(help_text="당첨 제한")
def gacha():
item_queryset = Item.objects.filter()
item_names = [str(item) for item in item_queryset]
weights = [item.weight for item in item_queryset]
limits = {str(item): item.global_limit for item in item_queryset}
reward_dict = {item: 0 for item in item_names}
for i in range(NUM_BATCHES):
results = gacha_pull_with_limit(item_names, weights, global_limits)
reward_dict[results] += 1
return reward_dict