Amit
Amit

Reputation: 7818

Randomly choose a number in a specific range with a specific multiple in python

I have the following numbers:

100, 200, 300, 400 ... 20000

And I would like to pick a random number within that range. Again, that range is defined as 100:100:20000. Furthermore, by saying 'within that range', I don't mean randomly picking a number from 100->20000, such as 105. I mean randomly choosing a number from the list of numbers available, and that list is defined as 100:100:20000.

How would I do that in Python?

Upvotes: 12

Views: 14864

Answers (4)

Tom Zych
Tom Zych

Reputation: 13576

For Python 3:

import random

random.choice(range(100, 20100, 100))

Upvotes: 6

sberry
sberry

Reputation: 131978

This would do it

print random.choice(xrange(100, 20100, 100);

But this is probably better:

print int(round(random.randint(100, 200001),-2))

@mouad's answer looks the best to me.

EDIT
Out of curiosity I tried a benchmark of this answer vs. random.randint(1, 2001) * 100 which it turns out is pretty much the exact same. A difference of about 1 - 2 hundredths of a second for 1M iterations.

Upvotes: 1

Guy L
Guy L

Reputation: 2954

from python manual:

random.randrange([start], stop[, step])

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

Upvotes: 2

mouad
mouad

Reputation: 70021

Use random.randrange :

random.randrange(100, 20001, 100)

Upvotes: 21

Related Questions