我无法正确回答答案。
return roll_dice(x)
语法是否正确,还是我需要用括号中的其他内容替换x
?
我是初学者,希望对此问题有所帮助:
我的代码:
import numpy as np
def roll_dice(x):
totmoney = 0
for a in range(x):
throw_one = np.random.randint(6)
throw_two = np.random.randint(6)
if throw_one % 2 != 0 or throw_two % 2 != 0:
totmoney += throw_one + throw_two
print throw_one,"|",throw_two,"|",totmoney
else:
totmoney -= throw_one + throw_two
print throw_one,"|",throw_two,"|",totmoney
return roll_dice(x)
答案 0 :(得分:1)
如果不做太多修改,我想你想做的是:
import random
def roll_dice(x):
totmoney = 0
result_matrix = []
for a in range(x):
throw_one = random.randint(1, 6)
throw_two = random.randint(1, 6)
if throw_one % 2 != 0 or throw_two % 2 != 0:
totmoney += throw_one + throw_two
print throw_one,"|",throw_two,"|",totmoney
else:
totmoney -= throw_one + throw_two
print throw_one,"|",throw_two,"|",totmoney
result_matrix.append([throw_one, throw_two, totmoney])
return result_matrix
example = roll_dice(2)
print example
(我使用了random模块,因为我没有安装numpy)
每次进行循环时,每次创建一行矩阵,最后这个矩阵就是你返回的。
但我会添加一些额外的修改:
import random
def roll_dice(x):
totmoney = 0
result_matrix = []
for a in range(x):
throws = [random.randint(1, 6), random.randint(1, 6)]
if throws[0] % 2 != 0 or throws[1] % 2 != 0:
totmoney += sum(throws)
else:
totmoney -= sum(throws)
print throws[0],"|",throws[1],"|",totmoney
result_matrix.append([throws[0], throws[1], totmoney])
return result_matrix
example = roll_dice(2)
print example
这就是我所采取的措施:
throws
sum
函数添加这两个投掷print
声明放在您的if
声明之外我们可以走得更远,但我已经厌倦了,我不想把你与更高级的东西混淆。