2013-11-23 133 views
0

嘿,我有一個課堂練習,我堅持,並會感謝任何幫助。該程序應該隨機選擇一個1-5之間的數字並循環,直到所有數字被選中。然後它應該重複約100次,以獲得平均得到所有五個數字所需的次數。我知道如何使用random.int,只是不知道如何編寫一個循環,當所有5個數字都被選中時它會中斷。任何形式的幫助都會很棒。謝謝Python隨機數循環

回答

1

這將做到這一點:

from random import randint 
a = [] 
for _ in range(100): 
    b = 0 
    c = set() 
    while len(c) < 5: 
     c.add(randint(1, 5)) 
     b += 1 
    a.append(b) 
d = round(sum(a)/len(a)) 
print("{}\nAverage loops: {}".format(c, d)) 

記錄在案版本:

# Import the `randint` function from `random`. 
from random import randint 
# This will hold the results that will later be used to calculate the average. 
a = [] 
# This loops 100 times (to get data for a calculation of the average). 
for _ in range(100): 
    # This will be the number of times the while-loop loops. 
    b = 0 
    # This is a set to hold the choices of `random.randint`. 
    # When it reaches 5 items, all numbers from 1-5 have been found. 
    c = set() 
    # Loop while the length of the set is less than 5. 
    while len(c) < 5: 
     # Add a new random number to the set, 
     # If the number is already there, nothing happens. 
     c.add(randint(1, 5)) 
     # Record a completed iteration of the while-loop. 
     b += 1 
    # Add the number of while-loop loops to `a`. 
    a.append(b) 
# The average is calculated by dividing the sum of `a` by the length of `a`. 
# It is then rounded to the nearest integer. 
d = round(sum(a)/len(a)) 
# Print the results. 
print("{}\nAverage loops: {}".format(c, d)) 

輸出示例:

{1, 2, 3, 4, 5} 
Average loops: 12 

{1, 2, 3, 4, 5} 
Average loops: 10 

{1, 2, 3, 4, 5} 
Average loops: 9 
2

我建議你使用Set。每次達到1-5之間的值時,將其放入您的設置中,然後當設置的大小爲5時,打破循環。

+1

很好的提示。實際上,在這裏你甚至不需要'休息'(有些新手可能還不知道),只需在'while'時用'length <5'作爲條件。' – abarnert

+0

而不是舊的,過時的套餐'模塊,爲什麼不使用內置'set'? – user2357112

+0

對不起,我已經鏈接了一個自2.6以來已棄用的類。這是正確的[set](http://docs.python.org/2/library/stdtypes.html#set) – Azeq

1

我只是做一個while循環,它產生一個1-5之間的隨機數,直到它得到第一個數字t,記錄它所花費的嘗試次數,記錄它所花費的嘗試次數。與下一個數字,當你完成後,找到平均花了多少次嘗試。

例子:

total = 0 
for i in range(100): 
    for n in range(1,6): 
     generatedNum = 0 
     while generatedNum != n: 
      #generate random number 
      total += 1 
print (total/100) 
0

這裏是另一種方式,我們可以使用:導致

import random 

total = {1:0,2:0,3:0,4:0,5:0} 

for k in xrange(100):       #outter loop 
    trial = {} 
    n = 0          #counter 
    while n<5: 
     sample = random.randint(1,5)   #sample 
     try: 
      trial[sample] += 1 
     except: 
      n += 1 
      trial[sample] = 1 
    for i in xrange(1,6):      #accumulate the results 
     total[i] += trial[i] 

>>> total 
{1: 221, 2: 255, 3: 246, 4: 213, 5: 243}