大家好,我刚刚开始学Python,请各位前辈帮帮忙,谢谢!!
这是我的Python作业,要求写代码通过老师给的测试文件才算成功。我做了半天,写了下面的代码,但是仍然通过不了测试程序。所以向大家求救一下……
这是题目:
#
文件名是dice.py"""这是一个关于投掷骰子的程序,一个骰子有六面,每面有1-6其中一个数字, 但是也允许有nsides(n面)的骰子"""
import random
def roll(nsides=6):
"""投掷一个nsides的骰子,返回一个 1到nsides的整数."""
nsides = int(nsides)
r = random.randint(0, nsides)
return r
def rollpair(nsides=6):
"""投掷一对nsides的骰子. 返回一对骰子,要以tuple的形式返回, 像(3, 6)."""
r1 = roll()
r2 = roll()
r = (r1, r2)
return r
def rolls(ntimes=10, nsides=6):
"""投掷一个nsides的骰子ntimes(n次). 返回一个list.
>>> import random; random.seed('downtown')
>>> rolls()
[2, 5, 4, 5, 4, 1, 6, 6, 2, 2]
"""
rlist = []
for n in range(ntimes):
rlist.append(roll())
return rlist
def rollpairs(ntimes=10, nsides=6):
"""投掷一对nsides的骰子ntimes. 返回一个list.
>>> import random; random.seed('pythonistas')
>>> rollpairs()
[(2, 6), (6, 2), (6, 4), (5, 5), (6, 3), (2, 4), (1, 3), (3, 4), (5, 6), (4, 5)]
"""
rplist = []
for n in range(ntimes):
rplist.append(rollpair())
return rplist
def dice_sum(pair):
""""返回一对骰子的值的总和.
>>> pair = (6, 1)
>>> dice_sum(pair)
7
"""
x, y = int()
pair [x, y]
s = x + y
return s
if __name__ == '__main__':
import doctest
doctest.testmod()
-----------------------------------------------------------------------------
下面是要通过的测试文件:
>>> from dice import roll, rollpair, rolls, rollpairs
>>> import random
>>> random.seed('pythonistas')
>>> rolls(ntimes=6)
[2, 6, 6, 2, 6, 4]
>>> rolls(ntimes=6)
[5, 5, 6, 3, 2, 4]
Roll 600 times.
>>> rolls(ntimes=600)
[1, 3, 3, 4, 5, 6, 4, 5, 6, ..., 6, 1, 3, 2, 2]
Roll a pair of dice 20 times.
>>> rollpairs(20)
[(4, 2), (3, 2), (4, 3), (4, 4), (2, 2), (3, 3), ..., (5, 3), (6, 1), (6, 1)]
Roll a pair of 20-sided dice 10 times.
>>> rollpairs(ntimes=10, nsides=20)
[(12, 11), (8, 4), (18, 12), (20, 9), (2, 19), (4, 19), (16, 8), (16, 4), (20, 3), (7, 5)]
>>> from dice import dice_sum
>>> pair = (6, 4)
>>> dice_sum(pair)
10
----------------------------------------------------------------------------------------
上面是我到目前为止写的roll, rollpair, rolls, rollpairs,sum这几个程序,但是通过不了测试,。我不明白那个随机数的顺序要怎样才和测试的程序一样。
这是错误信息:
File "tests/testA_dice.txt", line 9, in testA_dice.txt
Failed example:
rolls(ntimes=6)
Expected:
[2, 6, 6, 2, 6, 4]
Got:
[1, 5, 6, 5, 1, 5]
-----------------------------------------------------------------------------------------
还有sum里面的代码也有错误:
>>> def dice_sum(pair):
x, y = int()
pair [x, y]
s = int()
s = x + y
return s
>>> pair = (6, 1)
>>> dice_sum(pair)
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
dice_sum(pair)
File "<pyshell#106>", line 2, in dice_sum
x, y = int()
TypeError: 'int' object is not iterable
请问各位前辈怎么改?? 还有4天就要交作业了,这只是五个作业中的第一个,这个通过不了,后面的就别提了。请帮帮小弟,万分感谢!