From c3287780f247dfeeb6a606f17dd930f9e879d809 Mon Sep 17 00:00:00 2001 From: Geir Arne Hjelle Date: Thu, 21 Nov 2024 13:55:59 +0100 Subject: [PATCH] Add reverse_range() (#615) --- python-range/README.md | 16 ++++++++++++++++ python-range/reverse_range.py | 27 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 python-range/reverse_range.py diff --git a/python-range/README.md b/python-range/README.md index 138a72e91d..6b06fe92b6 100644 --- a/python-range/README.md +++ b/python-range/README.md @@ -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()`: diff --git a/python-range/reverse_range.py b/python-range/reverse_range.py new file mode 100644 index 0000000000..4b776905f1 --- /dev/null +++ b/python-range/reverse_range.py @@ -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))))