2017-11-18 120 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聲明

我們可以走得更遠,但我越來越疲憊,我不想把你和更先進的東西混淆。