Project 1: The Game of Hog--Problem 9 (2 pt)问题
问题9
Implement
max_scoring_num_rolls
, which runs an experiment to determine the number of rolls (from 1 to 10) that gives the maximum average score for a turn. Your implementation should usemake_averaged
androll_dice
.If two numbers of rolls are tied for the maximum average score, return the lower number. For example, if both 3 and 6 achieve a maximum average score, return 3.
You might find it useful to read the doctest and the example shown in the doctest for this problem before doing the unlocking test.
Important: In order to pass all of our tests, please make sure that you are testing dice rolls starting from 1 going up to 10, rather than from 10 to 1.
函数原型描述:
def max_scoring_num_rolls(dice=six_sided, samples_count=1000): """Return the number of dice (1 to 10) that gives the highest average turn score by calling roll_dice with the provided DICE a total of SAMPLES_COUNT times. Assume that the dice always return positive outcomes. >>> dice = make_test_dice(1, 6) >>> max_scoring_num_rolls(dice) 1 """ # BEGIN PROBLEM 9 "*** YOUR CODE HERE ***" # END PROBLEM 9
分析
这个函数想实现:给定一个dice()
,然后确定这个骰子扔多少个(num_rolls
)才能在函数make_averaged()
中获取最大平均值。
在这举个例子,看下函数roll_dice(num_rolls, dice)
以相同的点数策略dice()
,但是在不同的骰子数量num_rolls
的影响下,产生的结果。这里先固定下dice()
函数的策略:
>>> dice = make_test_dice(3, 1, 5, 6)
然后看下roll_dice(num_rolls, dice)
在不同的骰子数量num_rolls
的影响下(这里仅举1、2、3数量,其他数量可以自行推算💦),产生的结果:
num_rolls = 1
:反复调用roll_dice()
函数,省略各个骰子的结果,可以得到分数分别为:3、1、5、6。各个结果的概率均为1/4。num_rolls = 2
:反复调用roll_dice()
函数,省略各个骰子的结果,分数分别为1、11。得到每个结果的概率为1/2num_rolls = 3
:反复调用roll_dice()
函数,骰子的结果分别为:3,1,5
、6,3,1
、5,6,3
、1,5,6
、3,1,5
...这是4个得分循环,每次得分分别为:1、1、14、1。各个结果的概率均为1/4。
这个例子说明,函数roll_dice(num_rolls, dice)
在相同的点数策略dice()
,而在不同的骰子数量num_rolls
的影响下,重复调用会出现完全不一致的结果。这样就会导致函数make_averaged()
在选用相同点数策略但是不同骰子数量
的roll_dice()
时候,得到的结果不一致。
所以要确定:函数roll_dice(num_rolls, dice)
以相同的点数策略dice()
,但是以多少骰子数量num_rolls
才能在函数make_averaged()
获取到较大的平均值。
实现
def max_scoring_num_rolls(dice=six_sided, samples_count=1000): """Return the number of dice (1 to 10) that gives the highest average turn score by calling roll_dice with the provided DICE a total of SAMPLES_COUNT times. Assume that the dice always return positive outcomes. >>> dice = make_test_dice(1, 6) >>> max_scoring_num_rolls(dice) 1 """ # BEGIN PROBLEM 9 "*** YOUR CODE HERE ***" i = num_rolls = 1 higher_avg_score = 0 while i <= 10: avg_score = make_averaged(roll_dice, samples_count)(i, dice) if avg_score > higher_avg_score: higher_avg_score = avg_score num_rolls = i i += 1 return num_rolls # END PROBLEM 9
这样便通过了。
本文作者:上山砍大树
本文链接:https://www.cnblogs.com/shangshankandashu/articles/18022337
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步