2017-11-18 122 views
0

我无法正确地返回答案。如何正确返回?

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

'return roll_dice(x)'没有break语句,不改变'x'的值会导致无限递归循环。你需要在你的方法中创建一个嵌套列表来代表矩阵,然后返回该变量作为'return my_nested_list' – ZdaR

+0

我该怎么做呢? – ally1637

回答

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声明

我们可以走得更远,但我越来越疲惫,我不想把你和更先进的东西混淆。