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

生成随机长度随机整数列表报错原因排查求助

Hey there! Let's figure out why your code is throwing occasional errors and how to fix it for good.

Root Cause of the Error

The problem lies in this line of your code:

n2 = random.sample(range(1,40), random.randint(21,40))

The random.sample() function has a hard requirement: the number of elements you want to sample (the second argument) must be less than or equal to the total number of elements in the population you're sampling from (the first argument).

Here's the breakdown:

  • range(1,40) generates numbers from 1 to 39, which is 39 total elements.
  • random.randint(21,40) can produce values all the way up to 40. When it picks 40, you're asking sample() to grab 40 unique elements from a pool of only 39—this is impossible, which triggers the ValueError: Sample larger than population or is negative you've seen.

Your observation about larger ranges reducing error frequency makes perfect sense: if you use a bigger population (like range(1,100) which has 99 elements), even the maximum value from randint(21,40) (40) is way smaller than 99, so you never hit that conflict.

Fixes to Eliminate the Error

You have two reliable ways to fix this completely:

1. Hardcode the upper limit to match the population size

Since range(1,40) has exactly 39 elements, just set the upper bound of randint() to 39 instead of 40:

import random
n1 = random.sample(range(1,30), random.randint(5,20))
# range(1,40) has 39 elements, so cap the sample size at 39
n2 = random.sample(range(1,40), random.randint(21,39))
n3 = set(n1) & set(n2)
print(n3)

2. Dynamic population size calculation (more flexible)

If you might adjust the population ranges later, this approach avoids hardcoding. Calculate the size of your population first, then use that as the upper limit for randint():

import random
# Generate n1
pop1 = range(1,30)
# Sample between 5 and the total size of pop1 (29 elements)
n1 = random.sample(pop1, random.randint(5, len(pop1)))
# Generate n2
pop2 = range(1,40)
# Sample between 21 and the total size of pop2 (39 elements)
n2 = random.sample(pop2, random.randint(21, len(pop2)))
n3 = set(n1) & set(n2)
print(n3)

This way, no matter how you tweak pop1 or pop2 in the future, you'll never ask for more elements than exist in the population.

内容的提问来源于stack exchange,提问作者Mathew Coalson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:38:28