diff --git a/toolz/curried/__init__.py b/toolz/curried/__init__.py index 43aeffd4..5cc01fac 100644 --- a/toolz/curried/__init__.py +++ b/toolz/curried/__init__.py @@ -82,6 +82,7 @@ partitionby = toolz.curry(toolz.partitionby) pluck = toolz.curry(toolz.pluck) random_sample = toolz.curry(toolz.random_sample) +randint_range = toolz.curry(toolz.randint_range) reduce = toolz.curry(toolz.reduce) reduceby = toolz.curry(toolz.reduceby) remove = toolz.curry(toolz.remove) diff --git a/toolz/itertoolz.py b/toolz/itertoolz.py index 2462c5fb..0a1e06a7 100644 --- a/toolz/itertoolz.py +++ b/toolz/itertoolz.py @@ -14,7 +14,8 @@ 'first', 'second', 'nth', 'last', 'get', 'concat', 'concatv', 'mapcat', 'cons', 'interpose', 'frequencies', 'reduceby', 'iterate', 'sliding_window', 'partition', 'partition_all', 'count', 'pluck', - 'join', 'tail', 'diff', 'topk', 'peek', 'random_sample') + 'join', 'tail', 'diff', 'topk', 'peek', 'random_sample', + 'randint_range') def remove(predicate, seq): @@ -979,3 +980,27 @@ def random_sample(prob, seq, random_state=None): if not hasattr(random_state, 'random'): random_state = Random(random_state) return filter(lambda _: random_state.random() < prob, seq) + + +def randint_range(sample_size, min, max, random_state=None): + """ Generates a random sequence of integers from a specified range + + Returns a lazy iterator of random integers from a range. + + >>> list(randint_range(5, 100, 1000)) # doctest: +SKIP + [157, 196, 781, 882, 905] + >>> list(randint_range(5, 100, 1000)) # doctest: +SKIP + [234, 377, 501, 601, 885] + >>> list(randint_range(5, 100, 1000, random_state=2017)) + [270, 548, 595, 878, 999] + >>> list(randint_range(5, 100, 1000, random_state=2017)) + [270, 548, 595, 878, 999] + """ + if not hasattr(random_state, 'random'): + random_state = Random(random_state) + population_size = max - min + for i in range(min, max): + if random_state.random() < sample_size / population_size: + yield i + sample_size -= 1 + population_size -= 1