2016-10-16 35 views
0

我真的需要幫助。我定義了一個函數,可以爲n面骰子提供x個卷軸。現在我被要求計算每邊的頻率,並且freq1 += 1似乎沒有工作,考慮到可以有更多的方面(不只是6),我所做的是;如何調用隨機列表函數而無需在Python中進行鏈接?

我定義爲dice(x)第一功能,

freq_list = list(range(1,(n+1))) 
rollfreq = [0]*n 
for w in dice(x): 
    rollfreq[w-1] += 1 

print zip(freq_list,rollfreq) 

我得到一個列表,諸如[(1,0),(2,4),(3,1)...]等,預計,但問題是rollfreq衣被合計不匹配原始隨機生成dice(x)列表。我認爲這是因爲它是RNG,它在第二次運行中改變dice(x)的值,所以我不能參考我的原始隨機生成的dice(x)函數。有沒有解決這個問題的方法?我的意思是我嘗試了幾乎所有的東西,但它顯然不起作用!

編輯:

import random 

n = raw_input('Number of the sides of the dice: ') 
n = int(n) 
x = raw_input('Number of the rolls: ') 
x = int(x) 

def dice(): 
    rolls = [] 
    for i in range(x): 
     rolls.append(random.randrange(1, (n+1))) 
    return rolls 
print dice() 
freq_list = list(range(1,(n+1))) 
rollfreq = [0]*n 
for w in dice(): 
     rollfreq[w-1] += 1 

print 'The number of frequency of each side:', zip(freq_list,rollfreq) 

我添加的代碼 - 希望你們能幫助我弄清楚這一點,謝謝!

+0

骰子函數是你自己寫的東西嗎?你可以發佈代碼嗎? – n3m4nja

+0

謝謝你的回覆。我將代碼添加到OP。 – aleatha

+0

如何將卷的內容分配給變量? –

回答

0

您將dice()函數調用了兩次,當您打印該函數時,以及在for循環中迭代了一次。不同的結果來自那裏。

import random 

n = raw_input('Number of the sides of the dice: ') 
n = int(n) 
x = raw_input('Number of the rolls: ') 
x = int(x) 

def dice(): 
    rolls = [] 
    for i in range(x): 
     rolls.append(random.randrange(1, (n+1))) 
    return rolls 

freq_list = list(range(1,(n+1))) 
rollfreq = [0]*n 

# Grab the rolls 
rolls = dice() 
# Print them here 
print(rolls) 

for w in rolls: 
     rollfreq[w-1] += 1 

print 'The number of frequency of each side:', zip(freq_list,rollfreq) 
+0

nemanjap,非常感謝您的糾正,這正是我所需要的!我試圖打電話給它一次,但不知如何做到這一點:) – aleatha

相關問題