如何正确归还?

时间:2017-11-18 05:13:35

标签: python python-2.7 numpy

我无法正确回答答案。

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)

1 个答案:

答案 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声明之外

我们可以走得更远,但我已经厌倦了,我不想把你与更高级的东西混淆。