如何在python

我想在5分钟内生成随机数。之后,我想知道最常见的数字。

我的问题是:

1:如何在一段时间后手动中断代码(我不确定时间,时间很灵活,有时可能是5分钟30秒,有时可能是4分钟59秒),所以我更喜欢手动中断代码。

2:如何计算最常用的数字

每组数字均为4位数字。因此,我想生成数字0000而不是0

例如,我生成以下数字: 1:2578 2:3456 3:2578 4:9999 5:2578

我想找到最常见的数字2578。

以下是我的代码。

import random
while True:
    number=[random.randint(0,9)for value in range(0,4)]
    print(f"{number[0]}{number[1]}{number[2]}{number[3]}")

在阅读了会员给出的解决方案之后,我的解决方案如下:

import random
from collections import Counter
t_end = time.time() + 60*2
numbers = []
while time.time() < t_end:
    number=''.join(map(str,[random.randint(0,4)]))
    numbers.append(number)

print(Counter(numbers))

假设我将时间设置为2分钟,我可以在1分钟后终止脚本并获得结果吗?

iquw330860503 回答:如何在python

尝试一下:根据需要设置时间

[(54,74),(52,71),(83,66)]

输出:

        Color col;
        float red,green,blue,gray;

        for (int i = 0; i < oImage.Width; i++)
            for (int j = 0; j < oImage.Height; j++)
            {
                col = oImage.GetPixel(i,j);
                red = col.R;
                green = col.G;
                blue = col.B;
                gray = red*0.21 + green*0.72 + blue*0.07;


             oImage.SetPixel(i,j,Color.FromArgb(gray,gray,gray));

            }

        picImage.Refresh();
,

您可以尝试

import random
from collections import Counter

i=0
numbers = []
while i<100000:
    numbers.append(random.randint(0,9999))
    i += 1

print(Counter(numbers))

或者如果您想保留4位数格式:

import random
from collections import Counter

i=0
numbers = []
while i<1000:
    number=''.join(map(str,[random.randint(0,9)for value in range(0,4)]))
    numbers.append(number)
    i += 1

print(Counter(numbers))
,

尝试一下。

import time
import random 
from collections import Counter
from tqdm import tqdm

def most_common(a,b,top=5):
    start = time.time()
    rands = []

    time_in_min = 15
    print('Set maximum time is :',time_in_min,' minutes. You can stop before that')
    pbar = tqdm(total=1000)




    pbar = tqdm(total=1000)
    while time.time()-start<time_in_min*60:
        pbar.update(1000)
        rands.append(random.randint(a,b))
    pbar.close()
    rands = Counter(rands)
    return rands.most_common(top)

most_common(0,100,5)
#[(14,53415),(59,53269),(15,53229),(42,53223),(19,53222)]

本文链接:https://www.f2er.com/3153361.html

大家都在问