Last active
January 7, 2025 13:39
-
-
Save juandesant/6bcc27dbc33285d97c9829ec29d31687 to your computer and use it in GitHub Desktop.
Inclusive range (`irange`) using `range` as the basis
This file contains hidden or 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
| def irange(*args): | |
| """irange(stop) -> range object | |
| irange(start, stop[, step]) -> range object | |
| Returns a range object that produces a sequence of integers from start (inclusive) | |
| to stop (also inclusive) by step, which defaults to 1 | |
| irange(i, j) produces i, i+1, i+2, ..., j. (range would stop at j-1) | |
| start defaults to 0, and stop is omitted! irange(4) produces 0, 1, 2, 3, 4. | |
| When step is given, it specifies the increment (or decrement).""" | |
| start, stop, step = None, None, None | |
| num_args = len(args) | |
| # Decides how to process the arguments | |
| match num_args: | |
| case 1: # just a stop value | |
| stop = args[0] | |
| case 2: # start and stop value | |
| start = args[0] | |
| stop = args[1] | |
| case 3: # start, stop, and step | |
| start = args[0] | |
| stop = args[1] | |
| step = args[2] | |
| case _: | |
| raise ValueError("start, start and stop, or start, stop, and step values required.") | |
| if stop is not None and start is None: | |
| result = range(stop+1) | |
| if stop is not None and start is not None: | |
| if step is None: | |
| result = range(start, stop+1) | |
| else: | |
| if step > 0: | |
| result = range(start, stop+1, step) | |
| elif step < 0: | |
| result = range(start, stop-1, step) | |
| else: | |
| raise ValueError("step cannot be zero.") | |
| return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment