2013-02-26 41 views
-1

所以基本上我需要創建一個標記爲[0,1,2,3,4,5,10,25,100 ]。然後我需要在(0.75到4.75)+3之間創建隨機數。現在我需要打印一些東西,如「緩衝區3和平均值爲x秒」。 x將是生成的隨機數。每個緩衝區必須有它自己的隨機數Python:在創建隨機數字後,我如何將這些數字與我製作的列表相關聯

def main(): 
    buffer= [0,1,2,3,4,5,10,25,100] 
    time= random.uniform(0.75,4.75)+3 
    sum=0 
    for i in range (1, 500): 
     sum = sum + time; 
     average= sum/1500 
     for buffer in range(0,1,2,3,4,5,10,25,100): 
      print("For Buffer",buffer,",the average time is",average,".") 

[解決]

#Lab 1 using python. 
Import random #Importing random number generator. 
def main(): 
    buffers= [0,1,2,3,4,5,10,25,100]; #Defining the buffers using list. 
    for buffer in buffers: 
     sum=0; 

     for i in range (1, 500): # Create a loop which will create random number and increment 500 times. 
      time= (random.uniform (0.75,4.75))+3 
      sum = sum + time 

     average= sum/500; #Finding the average of each buffers random numbers. 

     print("For Buffer",buffer,",the average time is",average,"."); #Print the output. 
+1

我不是你問這裏是什麼100%清楚,但如果你想爲每個緩衝區提供不同的隨機數,你需要或者移動隨機數生成*內*您緩衝區環,或者您需要將所有隨機數存儲在某個地方(例如列表),然後在您的緩衝區for循環中迭代該數字。 – jam 2013-02-26 15:18:47

+0

爲什麼不'random.uniform(3.75,7.75)'? – Junuxx 2013-02-26 15:19:37

回答

1

你只需要改變它,你的平均計算在你的循環中完成。

buffer= [0,1,2,3,4,5,10,25,100] 
    for buffer in range(0,1,2,3,4,5,10,25,100): 
      sum=0 
      for i in range (1, 500): 
      time= random.uniform(0.75,4.75)+3 
      sum = sum + time; 
      average= sum/1500 
      print("For Buffer",buffer,",the average time is",average,".") 
+0

不應該在循環內部嗎?現在總和將是'time * 500',和'average == time/3',這沒有什麼意義。 – Junuxx 2013-02-26 15:21:57

+1

好的一點,我沒有看到計算,只是將代碼移到另一個循環中。將編輯以反映這個 – 2013-02-26 15:24:31

+0

我也懷疑在Dizzy的部分上500或1500是一個錯誤。 – Junuxx 2013-02-26 15:26:39

0

您可以將每個緩衝區與其平均值相關聯,使用一個字典使用緩衝區直接作爲鍵和值的平均值。

def main(): 
    buffer= [0,1,2,3,4,5,10,25,100] 
    time= random.uniform(0.75,4.75)+3 
    sum=0 
    dict_of_buffers = {} 
    for i in range (1, 500): 
     sum = sum + time; 
     average= sum/1500 
     for buffer in range(0,1,2,3,4,5,10,25,100): 
      print("For Buffer",buffer,",the average time is",average,".") 
      dict_of_buffers[buffer] = average 
相關問題