You need to enable JavaScript to run this app. 面向3万名单实现选4次水果时相同元素概率20%的代码方法
优惠活动
大模型
产品
解决方案
定价
更多

面向3万名单实现选4次水果时相同元素概率20%的代码方法

30000个姓名水果选择结果生成方案

核心实现逻辑

  • 先固定拆分分组规模:按总人数80%、20%的占比,将30000个姓名拆为两组,从根源上保证最终占比完全符合要求,避免逐人随机判断带来的比例随机波动。对应规模为24000个无重复场景名额、6000个带重复场景名额。
  • 打乱姓名列表顺序后再执行拆分,避免原列表排序带来的分组偏差。
  • 无重复组的选择结果采用不放回抽样生成,从机制上保证4个水果完全无重复。
  • 带重复组的选择结果采用有放回抽样生成,校验结果存在重复后才保留,完全覆盖列出的所有重复场景示例。

参考实现代码

import random
from collections import Counter

# 固定随机种子,保证结果可复现
random.seed(42)

# 基础配置
fruit_list = ["Apple", "Banana", "Orange", "Grape", "Kiwi", "Pineapple", "Watermelon", "Dragonfruit"]
total_name_count = 30000
no_repeat_group_ratio = 0.8
fruit_choice_count = 4
# 计算分组规模
no_repeat_group_size = int(total_name_count * no_repeat_group_ratio)
repeat_group_size = total_name_count - no_repeat_group_size

# 替换为自有姓名列表即可,以下为示例生成逻辑
name_list = [f"参与人_{idx}" for idx in range(total_name_count)]
# 打乱姓名顺序
random.shuffle(name_list)

# 拆分两组
no_repeat_group = name_list[:no_repeat_group_size]
repeat_group = name_list[no_repeat_group_size:]

# 生成无重复组的选择结果
final_result = {}
for name in no_repeat_group:
    # 不放回抽样4个水果,天然满足无重复要求
    final_result[name] = random.sample(fruit_list, k=fruit_choice_count)

# 生成带重复组的选择结果
for name in repeat_group:
    while True:
        # 有放回抽样4次
        choices = [random.choice(fruit_list) for _ in range(fruit_choice_count)]
        # 校验:只要存在重复即保留(覆盖所有带重复的场景)
        if len(set(choices)) < fruit_choice_count:
            # 如果需要严格满足"恰好1对重复"(即重复数为2,其余为1),将上面的判断替换为:
            # fruit_count = Counter(choices).values()
            # if sorted(fruit_count) == [1, 1, 2]:
            final_result[name] = choices
            break

# 结果校验
no_repeat_actual = sum(1 for res in final_result.values() if len(set(res)) == fruit_choice_count)
repeat_actual = total_name_count - no_repeat_actual
print(f"无重复结果数量:{no_repeat_actual},占比:{no_repeat_actual/total_name_count:.1%}")
print(f"带重复结果数量:{repeat_actual},占比:{repeat_actual/total_name_count:.1%}")

灵活调整说明

  • 当前代码默认覆盖列出的所有带重复的场景(含2个相同+2个不同、3个相同+1个不同、4个全相同的结果)。
  • 如果需要严格匹配“恰好出现1对重复元素”的定义(即仅存在一组重复,重复元素共2个,剩余2个水果互不重复,排除3个相同、4个全相同的结果),直接替换代码中标注的校验逻辑即可。
  • 30000人规模下的生成效率可满足要求:从8种水果中有放回抽4个,全不重复的概率约为41%,带重复组的校验重试次数极少,整体运行无性能压力。

内容的提问来源于stack exchange,提问作者JZG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 19:36:04