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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

NumIterator #321

Draft
wants to merge 11 commits into
base: master
Choose a base branch
from
Draft
Changes from 1 commit
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
Prev Previous commit
Next Next commit
checkpoint
  • Loading branch information
moshez committed Dec 12, 2022
commit b508d1c79a20fcbf8b9eedd3352d3ac2b407737a
45 changes: 45 additions & 0 deletions boltons/iterutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1524,6 +1524,51 @@ def _iter_or_num(thing: Union[Iterable[float], float]) -> Iterator[float]:

@dataclasses.dataclass
class NumIterator:

"""An iterator of numbers.

Supports math operations and slicing.

>>> list(NumIterator(range(3)))
[0, 1, 2]
>>> list(NumIterator(range(3)) + 1)
[1, 2, 3]
>>> list(NumIterator(range(3)) * 2)
[0, 2, 4]
>>> list(NumIterator(x + 1 for x in range(10))[:3])
[1, 2, 3]

There are also a few helper class methods to generate
common iterators.
They all generate *infinite* iterators.
Convert them to finite iterators using slicing.

Counting:

>>> list(NumIterator.count()[:5])
[0, 1, 2, 3, 4]

Constant:

>>> list(NumIterator.constant(7)[:2])
[7, 7]

Fibonacci sequence:

>>> list(NumIterator.fib()[:8])
[0, 1, 1, 2, 3, 5, 8, 13]

Since the iterators support math operations,
you can combine them to generate more sophisticated
sequences.

For example,

>>> fib_pow_of_2 = 2 ** NumIterator.count() + NumIterator.fib()
>>> list(fib_pow_of_2[:5])
[1, 3, 5, 10, 19]
"""

_original: Iterable[float]

@classmethod
Expand Down