gpt4 book ai didi

python - 如何生成没有连续数字的随机整数列表?

转载 作者:太空狗 更新时间:2023-10-30 01:18:12 25 4
gpt4 key购买 nike

在我对随机生成的列表进行排序后,我有连续的数字,例如

[7, 9, 13, 47, 64, 76, 83, 94, 95, 114, 115, 116, 120, 121, 123, 124, 127, 136, 152, 154, 167, 184, 189, 205, 212, 222, 226, 229, 231, 238]

这里连续的数字是(94, 95), (120, 121)(123, 124)。如何删除它们?

我的代码是:

while len(set(l)) != 30:
a = random.randint(1, 240)
l.append(a)

l = list(set(l))
l = sorted(l)

f.write(str(l))

我不想使用 random 模块中的 randrangechoice

最佳答案

创建一个随机数a并检查aa±1是否不在集合中:

import random 
l = set()
while len(l) != 30:
a = random.randint(1, 240)
if not {a-1,a,a+1} & l: # set intersection: empty == False == no common numbers
l.add(a)

l = sorted(l) # sorted creates a sorted list from any iterable

print(l)

输出:

[5, 12, 40, 47, 55, 59, 62, 73, 76, 82, 84, 89, 93, 95, 109, 
125, 127, 141, 165, 168, 184, 187, 196, 202, 204, 210, 215,
218, 229, 231]

直接使用集合可以非常快速地检查数字 (±1) 是否已经是随机数的一部分。

独库:


作为函数:

import random

def get_random_numbers_no_neighboring_elems(min_num, max_num, amount):
"""Generates amount random numbers in [min_num,..,max_num] that do not
include neighboring numbers."""

# this is far from exact - it is best to have about 5+ times the amount
# of numbers to choose from - if the margin is too small you might take
# very long to get all your "fitting numbers" as only about 1/4 of the range
# is a viable candidate (worst case):
# [1 2 3 4 5 6 7 8 9 10]: draw 2 then 5 then 8 and no more are possible
if (max_num-min_num) // 5 < amount:
raise ValueError(f"Range too small - increase given range.")

l = set()
while len(l) != amount:
a = random.randint(min_num, max_num)
if not {a-1,a,a+1} & l: # set intersection: empty == False == no commons
l.add(a)
return sorted(l)

print(get_random_numbers_no_neighboring_elems(1,240,80))

关于python - 如何生成没有连续数字的随机整数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54012213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com