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

Materials for Range tutorial #483

Merged
merged 2 commits into from
Jan 8, 2024
Merged
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
48 changes: 48 additions & 0 deletions python-range/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Python `range()`: Represent Numerical Ranges

This repository holds the code for Real Python's [Python `range()`: Represent Numerical Ranges](https://realpython.com/python-range/) tutorial.

## PiDigits

The file [`pi_digits.py`](pi_digits.py) shows the implementation of `PiDigits` which is an integer-like type that can be used as arguments to `range()`:

```python
>>> from pi_digits import PiDigits

>>> PiDigits(3)
PiDigits(num_digits=3)

>>> int(PiDigits(3))
314

>>> range(PiDigits(3))
range(0, 314)
```

See [the tutorial](https://realpython.com/python-range/#create-a-range-using-integer-like-parameters) for more details.

## FloatRange

In [`float_range.py`](float_range.py), you'll find an implementation of a custom `FloatRange` class that behaves similarly to the built-in `range()` except that its arguments can be floating point numbers:

```pycon
>>> from float_range import FloatRange

>>> FloatRange(1, 10, 1.2)
FloatRange(start=1, stop=10, step=1.2)

>>> list(FloatRange(1, 10, 1.2))
[1.0, 2.2, 3.4, 4.6, 5.8, 7.0, 8.2, 9.4]
```

The built-in `range()` is implemented in C. However, you can look at the source code of `FloatRange` to get an idea of how `range()` works under the hood.

If you need to work with floating-point ranges, you can use `FloatRange`. However, NumPy's [`arange()`](https://realpython.com/how-to-use-numpy-arange/) will give you better performance, and is probably a better option overall.

## Author

- **Geir Arne Hjelle**, E-mail: [[email protected]]([email protected])

## License

Distributed under the MIT license. See [`LICENSE`](../LICENSE) for more information.
113 changes: 113 additions & 0 deletions python-range/float_range.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
from dataclasses import dataclass, field
from math import ceil, isclose


@dataclass
class FloatRange:
"""Range of numbers that allows floating point numbers."""

start: float | int
stop: float | int | None = None
step: float | int = 1.0

def __post_init__(self):
"""Validate parameters."""
# Only one argument is given
if self.stop is None:
self.stop = self.start
self.start = 0

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If step is zero, we should raise an error to handle edge cases:

if math.isclose(self.step, 0):
    raise ValueError("'step' must not be zero")

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is checked by if not isinstance(self.step, float | int) or self.step == 0 below. I'm switching to isclose().

# Validate that all arguments are ints or floats
if not isinstance(self.start, float | int):
raise ValueError("'start' must be a floating point number")
if not isinstance(self.stop, float | int):
raise ValueError("'stop' must be a floating point number")
if not isinstance(self.step, float | int) or isclose(self.step, 0):
raise ValueError("'step' must be a non-zero floating point number")

def __iter__(self):
"""Create an iterator based on the range."""
return _FloatRangeIterator(self.start, self.stop, self.step)

def __contains__(self, element):
"""Check if element is a member of the range.

Use isclose() to handle floats.
"""
offset = (element - self.start) % self.step
if self.step > 0:
return self.start <= element < self.stop and (
isclose(offset, 0) or isclose(offset, self.step)
)
else:
return self.stop < element <= self.start and (
isclose(offset, 0) or isclose(offset, self.step)
)

def __len__(self):
"""Calculate the number of elements in the range."""
if any(
[
self.step > 0 and self.stop <= self.start,
self.step < 0 and self.stop >= self.start,
]
):
return 0
return ceil((self.stop - self.start) / self.step)

def __getitem__(self, index):
"""Get an element in the range based on its index."""
if index < 0 or index >= len(self):
raise IndexError(f"range index out of range: {index}")
return self.start + index * self.step

def __reversed__(self):
"""Create a FloatRange with elements in the reverse order.

Any number 0 < x < self.step can be used as offset. Use 0.1 when
possible as an "esthetically nice" offset.
"""
cls = type(self)
offset = (1 if self.step > 0 else -1) * min(0.1, abs(self.step) / 2)
return cls(
(self.stop - self.step) + (self.start - self.stop) % self.step,
self.start - offset,
-self.step,
)

def count(self, element):
"""Count number of occurences of element in range."""
return 1 if element in self else 0

def index(self, element):
"""Calculate index of element in range."""
if element not in self:
raise ValueError(f"{element} is not in range")
return round((element - self.start) / self.step)


@dataclass
class _FloatRangeIterator:
"""Non-public iterator. Should only be initialized by FloatRange."""

start: float | int
stop: float | int
step: float | int
_num_steps: int = field(default=0, init=False)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The iterator protocol requires that an iterator object implements the .__iter__() method as well:

Suggested change
def __iter__(self):
return self

Without it, you won't be able to loop over the iterator itself or pass it into a list():

>>> for value in _FloatRangeIterator(1, 3, 0.5):
...     print(value)
...
1.0
1.5
2.0
2.5

>>> it = _FloatRangeIterator(1, 3, 0.5)
>>> list(it)
[1.0, 1.5, 2.0, 2.5]

def __iter__(self):
"""Initialize the iterator."""
return self

def __next__(self):
"""Calculate the next element in the iteration."""
element = self.start + self._num_steps * self.step
if any(
[
self.step > 0 and element >= self.stop,
self.step < 0 and element <= self.stop,
]
):
raise StopIteration
self._num_steps += 1
return element
9 changes: 9 additions & 0 deletions python-range/pi_digits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from dataclasses import dataclass


@dataclass
class PiDigits:
num_digits: int

def __index__(self):
return int("3141592653589793238462643383279"[: self.num_digits])
Loading