Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Add a function for lazily generating integers #365

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions toolz/curried/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
27 changes: 26 additions & 1 deletion toolz/itertoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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