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

创建一个随机数a并检查a和a 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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值