-
Notifications
You must be signed in to change notification settings - Fork 5.3k
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||||||||
|
||||||||
# 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) | ||||||||
|
||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The iterator protocol requires that an iterator object implements the
Suggested change
Without it, you won't be able to loop over the iterator itself or pass it into a >>> 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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:
There was a problem hiding this comment.
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 toisclose()
.