简体   繁体   English

如何编写代码以生成随机数,随机数只能每 5 次打印一次

[英]How do I write code in order to generate random numbers in a way that a random number can only be printed once every 5 times

I've written code in python in order to generate random numbers between 110-115, 19 times.我已经在 python 中编写了代码,以便生成 110-115 之间的随机数 19 次。 The code works however I would like to add code that states that the same random numbers cannot be printed out next to each other, they can only be printed out after the other 5 numbers have been used.该代码有效,但是我想添加代码,说明相同的随机数不能彼此相邻打印,它们只能在使用其他 5 个数字后打印出来。 for example:例如:

[112, 113, 115, 110, 111, 114, 112, 113, 115, 110, 111, 114...] [112、113、115、110、111、114、112、113、115、110、111、114……]

until 19 values have been printed.直到打印了 19 个值。

I have the following code:我有以下代码:

import random

randomlist = []

for i in range(19):

n = random.randint(110,115)

randomlist.append(n)

print(*randomlist, sep = "\n")

Try this, to generate 19 nos where no repetition in 5 consecutive nos.试试这个,生成 19 个不重复的 5 个连续号码。

import random
randomlist = []
while len(randomlist) < 19:
    n = random.randint(110,115)
    if n not in randomlist[-5:]:
        randomlist.append(n)
    else:
        continue

Hope this helps...希望这可以帮助...

Try this below code, it will solve your problem.试试下面的代码,它会解决你的问题。

import random
randomlist = []
i = 0
number_of_values = 19

while len(randomlist) < number_of_values:
    n = random.randint(110,115)
    if n not in randomlist[-5:]:
        randomlist.append(n)
print(randomlist, sep = "\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM