Last active
August 30, 2019 07:55
-
-
Save Diapolo10/31f6b2c4856db2c2a8516a8a5163dc9b to your computer and use it in GitHub Desktop.
Python range-function example definition
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
#!/usr/bin/env python3 | |
from typing import Generator, Optional | |
from numbers import Real | |
def my_range(start: Real, stop: Optional[Real]=None, step: Real=1) -> Generator[Real, None, None]: | |
""" An example definition of Python 3's range-class as a function """ | |
# If only one argument was provided, use that | |
# argument as the goal and set start to 0 | |
if stop is None: | |
start, stop = 0, start | |
# Improves readability | |
current = start | |
# If start + n*step doesn't add up to exactly stop, | |
# this fixes that problem | |
stop += stop % step | |
# This ensures that the range isn't infinite | |
# by checking that start+step really approaches stop | |
if abs(start-stop) <= abs(start+step-stop): | |
raise StopIteration | |
# Until the goal is reached, keep yielding the current value | |
while current != stop: | |
yield current | |
current += step | |
if __name__ == '__main__': | |
for num in my_range(10): | |
print(num, end=' ') | |
print() | |
for num in my_range(1, 11): | |
print(num, end=' ') | |
print() | |
for num in my_range(0, 99, 2): | |
print(num, end=' ') | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment