Python随机数循环

时间:2013-11-23 01:32:18

标签: python

嘿,我有一个课堂练习,我坚持,并希望得到任何帮助。程序应该随机选择1-5之间的数字并循环直到所有数字都被选中。然后它应该重复大约100次,以给出获得所有五个数字所需的平均数。我知道如何使用random.int,只是不知道如何编写一个循环,当所有5个数字被选中时它会中断。任何形式的帮助都会很棒。谢谢

4 个答案:

答案 0 :(得分:3)

我建议您使用Set。每次达到1-5之间的值时,将其放入您的集合中,然后当集合的大小为5时,打破循环。

答案 1 :(得分:2)

这样做:

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 :(得分: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)

答案 3 :(得分: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}