You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中random_array函数设size为100+时卡顿原因问询

为什么random_array函数在size≥100时卡顿?

嘿,我来帮你拆解这个问题!你的代码里卡顿的根源完全出在random_array函数的实现上,咱们一步步捋清楚:

问题核心:超出范围的唯一数请求

你调用random_array(1, 100, 1, size)时,randrange(1, 100, 1)生成的是1到99之间的整数(因为randrange是左闭右开区间,high参数100不会被包含),这个范围内总共只有99个唯一的数。

  • 当size=99时,刚好能把所有数都取完,循环很快就结束了;
  • 但当size≥100时,程序会陷入无限循环:已经没有新的唯一数可以生成了,每次nexts都是已经在lst里的数,continue会让循环一直跑下去,永远满足不了len(lst)<size的条件,所以看起来就是“卡顿”了。

解决方案:两种改进思路

思路1:先生成所有候选数,再洗牌抽取(推荐)

这种方式更高效,也从根源上避免了无限循环的问题:

from collections import defaultdict
from random import choice, shuffle

def random_array(low, high, step, size):
    # 先生成所有符合条件的唯一数
    all_candidates = list(range(low, high, step))
    max_possible = len(all_candidates)
    
    # 处理size超过最大可能数的情况
    if size > max_possible:
        print(f"提示:最多只能生成{max_possible}个唯一数,已返回全部")
        return all_candidates
    
    # 打乱列表后取前size个
    shuffle(all_candidates)
    return all_candidates[:size]

def find_pair_from_two_list(a, b, val):
    b_dict = defaultdict(int)
    for i,v in enumerate(b):
        b_dict[v] = i
    for v in a:
        if (val - v) in b_dict:
            return v, val-v
    return -1, -1

arr1 = random_array(1, 100, 1, 99)
arr2 = random_array(1, 100, 1, 99)
val1 = choice(arr1)
val2 = choice(arr2)
val = val1 + val2
print(find_pair_from_two_list(arr1,arr2, val))

思路2:提前判断边界,避免无限循环

如果你想保留原来的随机生成逻辑,可以先计算最大可生成的唯一数数量,提前终止错误:

from collections import defaultdict
from random import randrange, choice

def random_array(low, high, step, size):
    lst = []
    max_possible = len(range(low, high, step))
    
    # 如果请求的数量超过上限,直接抛出错误
    if size > max_possible:
        raise ValueError(f"无法生成{size}个唯一数,该范围内最多有{max_possible}个")
    
    while len(lst)<size:
        nexts = randrange(low, high, step)
        if nexts in lst:
            continue
        lst.append(nexts)
    return lst

# 后续函数和调用逻辑不变...

这样当你不小心设置size超过上限时,程序会直接给出明确的错误提示,而不是卡住不动。

内容的提问来源于stack exchange,提问作者Raj Lath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:43:57