0

I'm working on a problem from this website:

https://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html

The exercise I'm working on asks us to generate two random integer lists of different lengths. Here is what I've got:

import random 
n1 = random.sample(range(1,30), random.randint(5,20))
n2 = random.sample(range(1,40), random.randint(21,40))
n3 = set(n1) & set(n2)
print(n3)

For some reason this runs sometimes and not others. Here is a screenshot of it not running. enter image description here It clearly has something to do with the size of the ranges because the larger I make them the less often I return an Error. But, I'd like to understand why it throws the error in the first place so I can avoid it all together.

Thanks in advance.

7
  • I really don't understand the misunderstanding here. What are you expecting this to do? Commented May 18, 2018 at 21:05
  • 5
    range() does not include the end value, random.randint() does. So it's possible that your n2 tries to sample 40 values from a range consisting of 39 elements. Commented May 18, 2018 at 21:05
  • @jasonharper except the sample only comes from 30 values, and the OP asks for 40 values. Commented May 18, 2018 at 21:08
  • If you have intermittent issues you should restart your Jupyter notebook, at minimum. Commented May 18, 2018 at 21:43
  • I'm not clear why this question was downvoted? Any thoughts? Commented May 19, 2018 at 20:15

2 Answers 2

3

random.sample(population,k) returns unique k elements from population

In your case, your population is [1,2,3,...39]. Your k = random.randint(21,40). So you will be getting an exception whenever the k value chosen is 40.

Sign up to request clarification or add additional context in comments.

Comments

2

This is documented for random.sample:

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Your screenshots show you use:

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

That means you could try to take up to 40 samples from a pool of 30 numbers which, without replacement, is not possible. The examples you gave in code in the actual question don't represent what you're trying to do in reality.

1 Comment

I'm going through this practice set of problems to learn Python, so yes it is likely that my code and my intentions do not line up exactly. Thank you for taking the time to respond.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.