如何高效生成指定区间子区域的唯一非零随机整数对?
问题:生成指定规则的唯一非零随机整数对
我需要从区间(-150, 151)中生成100个唯一的非零随机整数对,且要求按比例从不同子区域生成,目前我写的代码如下:
import random my_list = [] c = 0 while c < 100: if c < 5: # 两个数值不重复 first_num, second_num = random.sample(range(-5, 6), 2) # 排除0 while first_num == 0 or second_num == 0: first_num, second_num = random.sample(range(-5, 6), 2) c += 1 elif 5 <= c < 80: first_num, second_num = random.sample(range(-100, 101), 2) while first_num == 0 or second_num == 0: first_num, second_num = random.sample(range(-100, 101), 2) c += 1 else: first_num, second_num = random.sample(range(-150, 151), 2) while first_num == 0 or second_num == 0: first_num, second_num = random.sample(range(-150, 151), 2) c += 1 random_nums = (first_num, second_num) if random_nums not in my_list: my_list.append(random_nums) else: c -= 1
想请教有没有更优雅、高效的实现方式?
补充规则说明
和MatBailie讨论后,明确以下额外要求:
- 有序数对允许:比如
(5,6)和(6,5)算不同数对,但同一个数对不能重复出现; - 数对全局唯一:如果
(-1, 1)已经从(-5, 6)区间生成过,就不能再从更大的区间(比如(-100, 101)或(-150, 151))生成这个数对; - 跨区间数对允许:比如
(-1, 140)或(140, -1)这类一个数来自小区间、一个来自大区间的数对是允许的。
基准测试结果
对MatBailie、Alain T.和Samwise的实现做了性能测试:
- 生成100个数对时的性能对比:

- 生成1000个数对(保持子区域比例不变)时的性能对比:

内容的提问来源于stack exchange,提问作者plpm
相关产品推荐
相关产品推荐

