如何生成随机数,将它们放入字典中,然后返回重复次数

问题描述 投票:0回答:3

我的任务是创建一个计算随机数的函数,然后将其添加到字典中,直到再次随机生成此数字。因此,必须将重复次数打印到控制台中。

我已经尝试了以下但我没有得到结果。我是一名Python初学者,所以我也觉得有点失落。

import random
def repetition(a, b):
    d = dict()
    x = random.randint(a ,b)
    for i in d:
        if x in d.values:
            return len(dict)
        else:        
            dict.update(x)

在最后一步中,结果应该被格式化为生成的数字的元组,然后最后但并非最不重要的重复次数可能如下所示:

repetition(2, 5255)
([1244, 2415, ... ], 122)
python random
3个回答
0
投票

这可能有所帮助!

def repetition(a, b):
    d = {}
    while 1:
        x = random.randint(a, b)
        if x in d:
            return list(d.values()), len(d)
        d[x] = x

0
投票
import random
def repetition(a, b):
   x = random.randint(a ,b)
   y = None
   values = [x]
   i = 0
   while x != y:
      y = random.randint(a,b)
      values.append(y)
      i += 1
return((values, i))

这应该返回你所期望的,但我没有使用任何字典。


0
投票

也许你可以使用collections.Counter。什么是返回列表中的数字量。这是我如何工作的一个例子。

import collections

x = [10,10,20,10,20]
c = collections.Counter(x)
print(c[10])
© www.soinside.com 2019 - 2024. All rights reserved.