r/DailyCodingProblem • • Apr 06 '22

Daily Coding Problem: Problem #10 [Medium] - 2022-04-05

Good morning! Here's your coding interview problem for today.

This problem was asked by Apple.

Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.

1 Upvotes

1 comment sorted by

1

u/T4ll1n Apr 06 '22

Here is my solution.


from time import sleep


def scheduler(f, n, f_kw_args):
    sleep(1 / (n / 1000))
    f(**f_kw_args)


scheduler(lambda x: print(x * 2), 500, {"x": 4})


# that can't be it, I probably miss something

# If I had to write something like that seriously, I would use a decorator to keep the
# timing completely separate from the function.

def scheduler_decorator(n):
    def Inner(func):
        def wrapper(*args, **kwargs):
            # sleep for n milliseconds
            sleep(1 / (n / 1000))
            res = func(*args, **kwargs)

            return res

        return wrapper

    return Inner


@scheduler_decorator(100)
def f():
    return "cool"


f()