Skip to content

Commit

Permalink
Add reverse_range() (#615)
Browse files Browse the repository at this point in the history
  • Loading branch information
gahjelle authored Nov 21, 2024
1 parent 7f54af4 commit c328778
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
16 changes: 16 additions & 0 deletions python-range/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@

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

## reverse_range()

In [`reverse_range.py`](reverse_range.py), you can find an explicit implementation of a function that can reverse a general range.

```python
>>> from reverse_range import reverse_range

>>> reverse_range(range(1, 20, 4))
range(17, 0, -4)

>>> list(reverse_range(range(1, 20, 4)))
[17, 13, 9, 5, 1]
```

In practical applications, you should use `reversed(range(1, 20, 4))` or `range(1, 20, 4)[::-1]` instead.

## 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()`:
Expand Down
27 changes: 27 additions & 0 deletions python-range/reverse_range.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def reverse_range(rng):
"""Explicitly calculate necessary parameters to reverse a general range.
In practice, you should use reversed() or [::-1] instead.
"""
adj = 1 if rng.step > 0 else -1
return range(
(rng.stop - adj) - (rng.stop - rng.start - adj) % rng.step,
rng.start - adj,
-rng.step,
)


if __name__ == "__main__":
numbers = range(1, 20, 4)

print("\nOriginal:")
print(numbers)
print(list(numbers))

print("\nReversed:")
print(reverse_range(numbers))
print(list(reverse_range(numbers)))

print("\nTwice reversed, has the same elements as the original:")
print(reverse_range(reverse_range(numbers)))
print(list(reverse_range(reverse_range(numbers))))

0 comments on commit c328778

Please sign in to comment.