0 から 9 までのランダムな整数 (両端を含む) を生成したいのですが、同じ数値が連続して生成されないようにしたいと考えています。モジュールのrandint
関数を使用する予定です。random
しかし、それが便利になるかどうかはわかりません。はどのくらいの頻度random.randint
で同じ数を生成しますか?
6396 次
5 に答える
4
randintをラップしないのはなぜですか?
class MyRand(object):
def __init__(self):
self.last = None
def __call__(self):
r = random.randint(0, 9)
while r == self.last:
r = random.randint(0, 9)
self.last = r
return r
randint = MyRand()
x = randint()
y = randint()
...
于 2012-06-19T09:20:09.423 に答える
3
Python のドキュメントでランダムと書かれている場合は、特に明記されていない限り、一様にランダムであることを意味すると想定できます (つまり、考えられるすべての結果の確率は同じです)。
連続した数字を生成せずに数字を生成するための最も簡単なオプションは、独自のジェネレーターを作成することです。
def random_non_repeating(min, max=None):
if not max:
min, max = 0, min
old = None
while True:
current = random.randint(min, max)
if not old == current:
old = current
yield current
于 2012-06-19T09:13:33.920 に答える
2
これは while ループなしで簡単に実行できます。
next_random_number = (previous_random_number + random.randint(1,9)) % 10
于 2012-06-19T17:43:35.773 に答える
2
重複を避けるために、次のような単純なラッパーを使用できます (これがどのように機能するかについての説明は、Fisher-Yatesを参照してください)。
def unique_random(choices):
while True:
r = random.randrange(len(choices) - 1) + 1
choices[0], choices[r] = choices[r], choices[0]
yield choices[0]
使用例:
from itertools import islice
g = unique_random(range(10))
print list(islice(g, 100))
于 2012-06-19T09:29:18.870 に答える