如何解决如何修改优惠券收集器问题的蒙特卡罗模拟代码
我要解决的问题是,如果我每天随机收到 1/5 张优惠券,那么这 5 张优惠券各领取 2 份需要多少天?
我的代码只检查每张优惠券中的一张,而不是两张,但我不确定在哪里可以进行修改。我编辑了 while True 语句以在我的 card_own 语句中包含一个列表,例如 cards_own != [1,1,2,3,4,5,5]
但是我的输出根本没有打印。我想也许使用 random.choice 函数会是一个更好的选择。有什么推荐吗?
import numpy as np
# number of simulations
n =10000
# defining function to check if we got all 5 cards indexed from 0 to 4
def all_cards(arr2,arr1=np.array(range(5))):
return np.array_equal(arr1,arr2)
days_taken = 0
# performing simulation
for i in range(n):
# initializing empty list to store card obtained in each day
cards_own =[]
# days taken in each simulation
days =1
# looping until i get 5 cards and count the days taken for finding average
while True:
value = np.random.randint(0,5)
cards_own.append(value)
if len(cards_own)>=5:
if all_cards(arr2=np.array(list(set(cards_own)))):
days_taken+=days
break
days+=1
average = days_taken/n
# recording the result in result with given precision
result = round(average,2)
print("Average days taken = ",result," days")
解决方法
因此,我认为您可以在这里更改一些内容。首先,您可以将 if 语句更改为 if len(cards_own) >= 10
,因为您需要至少 10 张优惠券才能拥有 2 个。此外,在您的 cards_all
函数中,您可以遍历所有可能的优惠券(在本例中为 [0,4] 并检查数组中的每个优惠券是否至少出现两次(因此您不不需要arr2
)。例如:
for i in range(5):
if np.sum(arr1 == i) < 2:
return False
return True
if 语句只是计算元素 i 在数组中出现的次数。此外,您不应该在函数调用中将 arr1
转换为集合,因为集合不能有重复的值,因此检查每个优惠券的 2 个永远不会像那样工作。希望这会有所帮助!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。