开发者

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

开发者 https://www.devze.com 2023-04-04 17:26 出处:网络
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开发者_如何学C. Furthermore, by sa

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开发者_如何学C. 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?


Use random.randrange :

random.randrange(100, 20001, 100)


For Python 3:

import random

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消