Problem 1 (200pts)
在hog.py中实现roll_dice函数。
它接受两个参数:一个正整数num_rolls,表示要掷骰子的次数,和一个dice函数。
它返回在一轮中掷骰子指定次数所得到的得分:要么是结果的总和,要么是1(由于Pig Out规则)。
要获得单次掷骰子的结果,请调用dice()。
您应该在roll_dice的函数体中恰好调用dice() num_rolls次。
请记住,即使在掷骰过程中发生Pig Out,也要恰好调用dice() num_rolls次。
这样可以正确地模拟同时掷所有骰子。
注意:
roll_dice函数以及项目中的许多其他函数都使用了默认参数值——您可以在函数定义中看到这一点:
python def roll_dice(num_rolls, dice=six_sided): ...参数
dice=six_sided表示当调用roll_dice时,dice参数是可选的。如果没有提供dice的值,则默认使用six_sided。例如,调用
roll_dice(3, four_sided),或者等效地roll_dice(3, dice=four_sided),模拟掷3个四面骰子,而调用roll_dice(3)模拟掷3个六面骰子。
理解问题:
在编写任何代码之前,请解锁测试以验证您对问题的理解。注意:在解锁相应问题的测试用例之前,您无法使用ok测试您的代码。
python ok -q 01 -u
编写代码并检查您的工作: 解锁完成后,开始实现您的解决方案。您可以使用以下命令检查正确性:
python ok -q 01
Solutions
def roll_dice(num_rolls, dice=six_sided):
ans = 0
pig_out = False
for _ in range(num_rolls):
cur = dice()
if cur == 1:
pig_out = True
ans += cur
if pig_out:
ans = 1
return ans
one-liner:
def roll_dice(num_rolls, dice=six_sided):
return (lambda x: 1 if min(x) == 1 else sum(x))([dice() for _ in num_rolls])