我正在为CS61A做第一个Hog项目,CS61A是加州大学伯克利分校的CS入门课程,在线发布所有材料,以自学CS(链接:https://inst.eecs.berkeley.edu/\~cs61a/sp20/(对于它的第一个问题,它要求我实现一个函数,该函数基本上会掷骰子特定次数,并返回所有数字的总和,除非其中一个骰子给出数字1,在这种情况下,该函数将返回1。
我有两个版本的代码。第一个版本有问题,但第二个版本通过了测试:
第一个版本:
def roll_dice(num_rolls, dice=six_sided):
"""Simulate rolling the DICE exactly NUM_ROLLS > 0 times. Return the sum of
the outcomes unless any of the outcomes is 1. In that case, return 1.
num_rolls: The number of dice rolls that will be made.
dice: A function that simulates a single dice roll outcome.
"""
# These assert statements ensure that num_rolls is a positive integer.
assert type(num_rolls) == int, 'num_rolls must be an integer.'
assert num_rolls > 0, 'Must roll at least once.'
# BEGIN PROBLEM 1
"*** YOUR CODE HERE ***"
# END PROBLEM 1
sum, k = 0, 1
pig_out = False
while k <= num_rolls:
curr = dice()
if curr == 1:
pig_out = True
else:
sum += curr
k += 1
if pig_out:
return 1
else:
return sum
第二个版本:
def roll_dice(num_rolls, dice=six_sided):
"""Simulate rolling the DICE exactly NUM_ROLLS > 0 times. Return the sum of
the outcomes unless any of the outcomes is 1. In that case, return 1.
num_rolls: The number of dice rolls that will be made.
dice: A function that simulates a single dice roll outcome.
"""
# These assert statements ensure that num_rolls is a positive integer.
assert type(num_rolls) == int, 'num_rolls must be an integer.'
assert num_rolls > 0, 'Must roll at least once.'
# BEGIN PROBLEM 1
"*** YOUR CODE HERE ***"
# END PROBLEM 1
sum, k = 0, 1
pig_out = False
while k <= num_rolls:
curr = dice()
if curr == 1:
pig_out = True
sum += curr
k += 1
if pig_out:
return 1
else:
return sum
在第一个例子中,如果我在python intelpreter中运行roll_dice(1,make_test_dice(2,3,4((,它会给我3,而它应该给我2(make_test_dice((返回一个骰子,它按照预先指定的顺序给出数字。例如,如果我运行make_test_dice(2,3,4(((一次,make_test_dice(2、3、4(会给出2,如果运行2次,会给出3,如果运行3次,会得到4(。如果我只运行一次,Python似乎会跳过第一个数字,但我不知道为什么。我怀疑这与其他声明有关,但我不确定为什么会引起这样的问题。。。。如有任何信息,我们将不胜感激!
我在问题的正文中具体说明了我所尝试的内容。
您似乎不可能得到不同的结果。你运行它时可能有不同的设置?除非你分享测试用例,否则我们真的帮不了多少忙。
您的代码似乎过于复杂。这更简单:
def roll_dice(num_rolls, dice=six_sided):
"""Simulate rolling the DICE exactly NUM_ROLLS > 0 times. Return the sum of
the outcomes unless any of the outcomes is 1. In that case, return 1.
num_rolls: The number of dice rolls that will be made.
dice: A function that simulates a single dice roll outcome.
"""
# These assert statements ensure that num_rolls is a positive integer.
assert type(num_rolls) == int, 'num_rolls must be an integer.'
assert num_rolls > 0, 'Must roll at least once.'
# BEGIN PROBLEM 1
"*** YOUR CODE HERE ***"
# END PROBLEM 1
sum = 0
for _ in range(num_rolls):
curr = dice()
if curr == 1:
return 1
sum += curr
return sum