Python案例如何实现随机抽奖?

wen python案例 44

本文目录导读:

Python案例如何实现随机抽奖?

  1. 方法一:使用random.choice() - 单次抽奖
  2. 方法二:带权重的抽奖系统
  3. 方法三:大转盘抽奖
  4. 方法四:完整抽奖系统(带历史记录)
  5. 实际应用建议
  6. 简单命令行版本

我来介绍几种Python实现随机抽奖的常用方法:

使用random.choice() - 单次抽奖

import random
# 准备奖品和参与者
prizes = ['一等奖:iPhone 15', '二等奖:AirPods', '三等奖:保温杯']
participants = ['张三', '李四', '王五', '赵六', '钱七']
# 简单随机抽奖
winner = random.choice(participants)
prize = random.choice(prizes)
print(f"恭喜 {winner} 获得 {prize}")

带权重的抽奖系统

import random
class LotterySystem:
    def __init__(self):
        self.participants = []
        self.prizes = []
    def add_participant(self, name, weight=1):
        """添加参与者,weight为权重(中奖概率)"""
        self.participants.append({'name': name, 'weight': weight})
    def add_prize(self, name, quantity):
        """添加奖品"""
        self.prizes.append({'name': name, 'quantity': quantity})
    def draw_one(self):
        """抽取一个中奖者"""
        if not self.participants:
            return None
        # 根据权重选择
        weights = [p['weight'] for p in self.participants]
        winner = random.choices(self.participants, weights=weights, k=1)[0]
        return winner['name']
    def draw_with_prizes(self):
        """抽取所有奖品"""
        results = []
        remaining_prizes = [p for p in self.prizes if p['quantity'] > 0]
        while remaining_prizes and self.participants:
            # 随机选择一个奖品
            prize = random.choice(remaining_prizes)
            # 抽奖
            winner = self.draw_one()
            if winner:
                self.participants = [p for p in self.participants if p['name'] != winner]
                prize['quantity'] -= 1
                results.append(f"🎉 {winner} 获得 {prize['name']}")
                # 更新剩余奖品
                remaining_prizes = [p for p in self.prizes if p['quantity'] > 0]
        return results
# 使用示例
lottery = LotterySystem()
# 添加参与者(可以设置权重)
lottery.add_participant('张三', weight=2)  # 中奖概率更高
lottery.add_participant('李四', weight=1)
lottery.add_participant('王五', weight=1)
lottery.add_participant('赵六', weight=0.5)  # 中奖概率较低
# 添加奖品
lottery.add_prize('一等奖:iPhone', 1)
lottery.add_prize('二等奖:iPad', 2)
lottery.add_prize('三等奖:蓝牙耳机', 3)
# 开始抽奖
results = lottery.draw_with_prizes()
for result in results:
    print(result)

大转盘抽奖

import random
import time
class WheelLottery:
    def __init__(self):
        self.items = []
    def add_sector(self, name, weight):
        """添加转盘扇区"""
        self.items.append({'name': name, 'weight': weight})
    def spin(self):
        """模拟转盘旋转并返回结果"""
        print("转盘转动中...")
        time.sleep(1)
        # 模拟转盘旋转效果
        for i in range(3):
            print(f"{'=' * (i+1)} 转盘中...")
            time.sleep(0.5)
        # 选择结果
        names = [item['name'] for item in self.items]
        weights = [item['weight'] for item in self.items]
        result = random.choices(names, weights=weights, k=1)[0]
        return result
# 使用示例
wheel = WheelLottery()
wheel.add_sector('一等奖:海南双人游', 1)
wheel.add_sector('二等奖:电动牙刷', 5)
wheel.add_sector('三等奖:电影票', 20)
wheel.add_sector('谢谢参与', 74)
result = wheel.spin()
print(f"🎊 恭喜您获得:{result}")

完整抽奖系统(带历史记录)

import random
import json
from datetime import datetime
class CompleteLotterySystem:
    def __init__(self):
        self.participants = []
        self.prizes = []
        self.history = []
    def add_participants(self, names):
        """批量添加参与者"""
        for name in names:
            self.participants.append({
                'name': name,
                'id': f'P{len(self.participants)+1:04d}'
            })
    def add_prizes(self, prizes_list):
        """批量添加奖品"""
        for name, count in prizes_list:
            self.prizes.append({
                'name': name,
                'count': count
            })
    def draw_by_category(self, category):
        """按类别抽奖"""
        # 获取剩余该类别奖品
        available_prizes = [p for p in self.prizes if p['count'] > 0]
        if not available_prizes:
            return None
        # 随机选择一个奖品
        prize = random.choice(available_prizes)
        # 从参与者中抽取
        if not self.participants:
            return None
        winner = random.choice(self.participants)
        self.participants.remove(winner)
        prize['count'] -= 1
        # 记录历史
        record = {
            'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'winner': winner['name'],
            'prize': prize['name'],
            'category': category
        }
        self.history.append(record)
        return record
    def save_history(self, filename='lottery_history.json'):
        """保存抽奖历史"""
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(self.history, f, ensure_ascii=False, indent=2)
        print(f"历史记录已保存至 {filename}")
# 使用示例
system = CompleteLotterySystem()
# 添加参与者
names = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
system.add_participants(names)
# 添加奖品
prizes = [
    ('iPhone 15 Pro', 1),
    ('AirPods Pro', 2),
    ('星巴克礼品卡', 5)
]
system.add_prizes(prizes)
# 进行抽奖
print("=== 年会抽奖系统 ===")
for _ in range(3):
    result = system.draw_by_category('普通奖')
    if result:
        print(f"⭐ {result['winner']} 获得 {result['prize']}")
    else:
        print("奖品已抽完或参与者不足")
# 保存历史
system.save_history()

实际应用建议

# 防止重复中奖的抽奖系统
class FairLottery:
    def __init__(self):
        self.all_participants = set()
        self.winners = set()
    def lottery(self, participants, num_winners):
        """公平抽奖,确保不重复中奖"""
        available = list(participants - self.winners)
        if len(available) < num_winners:
            print("参与人数不足!")
            return []
        winners = random.sample(available, num_winners)
        self.winners.update(winners)
        return winners
# 使用示例
lottery = FairLottery()
all_users = {'张三', '李四', '王五', '赵六', '钱七', '孙八'}
# 第一轮抽奖
winners1 = lottery.lottery(all_users, 2)
print(f"第一轮中奖者:{winners1}")
# 第二轮抽奖(不会重复中奖)
winners2 = lottery.lottery(all_users, 2)
print(f"第二轮中奖者:{winners2}")

简单命令行版本

import random
def simple_lottery():
    print("=== 简易抽奖系统 ===")
    # 输入参与者
    participants = []
    print("请输入参与者姓名(输入'结束'完成输入):")
    while True:
        name = input()
        if name == '结束':
            break
        if name.strip():
            participants.append(name.strip())
    if not participants:
        print("没有参与者!")
        return
    # 输入奖品
    print(f"共{len(participants)}人参与,请输入中奖人数:")
    try:
        num = int(input())
        if num > len(participants):
            print("中奖人数不能超过参与人数!")
            return
        # 抽奖
        winners = random.sample(participants, num)
        print("🎉 中奖名单:")
        for i, winner in enumerate(winners, 1):
            print(f"{i}. {winner}")
    except ValueError:
        print("请输入有效数字!")
# 运行
simple_lottery()

这些方法可以根据实际需求选择合适的实现方式:

  1. 简单抽奖:使用 random.choice()random.sample()
  2. 加权抽奖:使用 random.choices() 带权重参数
  3. 防重复抽奖:记录已中奖者
  4. 完整系统:结合文件存储、历史记录等

需要我帮你定制某种特定场景的抽奖系统吗?

抱歉,评论功能暂时关闭!