python - 概率算法

标签 python algorithm redis

我有一道概率算法题

目标是获得一个包含三个项目的列表。作为 FinalList

有四个源列表。

ALIST、BLIST、CLIST、DLIST

都是Unknown length。它们包含独特的元素

(其实程序一开始都是空的,从redis排序的list中得到,运行的时候,有增长)

从这个来源列表中选择项目。挑选随机元素生成FinalList

确保满足以下要求

在FinalList中,

  • ALIST 的项目出现的概率是 43%
  • BLIST 元素出现的概率是 37%
  • CLIST 的元素出现的概率是 19%
  • DLIST 的项目出现的概率是 1%

我已经写了一些代码,但这只是因为四个列表有很多元素。

from random import choice

final_list = []
slot = []

a_picked_times = 0

while a_picked_times < 43:
    item = choice(ALIST)
    ALIST.remove(item)

    if item in already_picked_list:
        continue

    slot.append(item)
    a_picked_times += 1


b_picked_times = 0

while b_picked_times < 37:
    ...

SOME CODE SIMILAR

# now slot is a list which contains 100 elements, 
# in slot, there are 43 elements of ALIST'items, 37 of B, 19 of C, 1 of D

for i in range(3):
    final_list.append( choice(slot) )

所以,这样可以保证概率的要求。 但前提是:这四个列表有很多元素。

list.remove( item ) 不会删除列表中的所有元素,因此我们将根据需要的时间正确拾取项目。

当A、B、C、D为空OR元素不足时,如何保证概率要求?

A、B、C、D列表都是从redis排序列表中获取的。或者使用 redis 的一些解决方案?

最佳答案

(对于每个元素)选择一个 1 到 100 之间的数字,然后根据该数字选择一个源列表可能更有意义。

关于python - 概率算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12123639/

相关文章:

python - 将两个 numpy 掩码数组加在一起

python - 如何将值更改为零但不在循环的第一次迭代中

algorithm - 使用尾递归在 Scala 中实现 isPrime

c++ - 生成类唯一标识的有效方法?

python - 如何使用 ldap3 python 模块强制用户在下次登录时更改密码?

algorithm - 如何解决 "Crypt Kicker"中提出的 "Programming Challenges (The Programming Contest Training Manual)"练习?

ruby-on-rails - 如何从 Redis 排序集中弹出?

Redis保存错误

node.js - node_redis 获取 zrange withscores

python - 无法让 Scrapy 跟踪链接