write the function _sleep_r in python

Here's an implementation of the _sleep_r function in Python:

main.py
import time

def _sleep_r(seconds, remainder=None):
    """
    Sleeps for the given amount of seconds and returns the remaining time to sleep
    """
    if remainder is None:
        remainder = seconds

    start = time.monotonic()
    time.sleep(remainder)
    end = time.monotonic()

    elapsed = end - start
    remaining = seconds - elapsed

    if remaining > 0:
        return _sleep_r(seconds, remaining)
    else:
        return 0
443 chars
21 lines

This uses the time module to sleep for the given amount of time, and keeps track of the remaining time to sleep until the full amount of time has elapsed. It recursively calls itself with the remaining time until there is no more time left to sleep.

related categories

gistlibby LogSnag