From e0334d3c0f8f333232fc69442fadb3e9f4701fe3 Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Mon, 7 Jan 2019 09:24:19 +0100 Subject: [PATCH] Test(core): doctest reject_random and filter_random --- mapytex/calculus/core/random.py | 59 ++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/mapytex/calculus/core/random.py b/mapytex/calculus/core/random.py index 431518b..b4187cb 100644 --- a/mapytex/calculus/core/random.py +++ b/mapytex/calculus/core/random.py @@ -10,7 +10,7 @@ Function to create random things """ -from random import randint, choice +import random __all__ = ["reject_random", "filter_random", "FilterRandom"] @@ -27,12 +27,37 @@ def reject_random(min_value = -10, :param rejected: rejected values :param accept_callbacks: list of function for value rejection + :example: + >>> a = reject_random() + >>> a not in [0, 1] + True + >>> a >= -10 + True + >>> a <= 10 + True + >>> a = reject_random(min_value=3, max_value=11, rejected=[5, 7]) + >>> a not in [5, 7] + True + >>> a >= 3 + True + >>> a <= 11 + True + >>> a = reject_random(accept_callbacks=[lambda x: x%2]) + >>> a%2 + 1 + >>> random.seed(0) + >>> reject_random() + 2 + >>> random.seed(1) + >>> reject_random() + -6 + """ conditions = [lambda x: x not in rejected] + accept_callbacks - candidate = randint(min_value, max_value) + candidate = random.randint(min_value, max_value) while not all(c(candidate) for c in conditions): - candidate = randint(min_value, max_value) + candidate = random.randint(min_value, max_value) return candidate @@ -49,6 +74,30 @@ def filter_random(min_value = -10, :param rejected: rejected values :param accept_callbacks: list of function for value rejection + :example: + >>> a = filter_random() + >>> a not in [0, 1] + True + >>> a >= -10 + True + >>> a <= 10 + True + >>> a = filter_random(min_value=3, max_value=11, rejected=[5, 7]) + >>> a not in [5, 7] + True + >>> a >= 3 + True + >>> a <= 11 + True + >>> a = filter_random(accept_callbacks=[lambda x: x%2]) + >>> a%2 + 1 + >>> random.seed(0) + >>> filter_random() + -7 + >>> random.seed(1) + >>> filter_random() + 6 """ candidates = set(range(min_value, max_value+1)) candidates = {c for c in candidates if c not in rejected} @@ -58,7 +107,7 @@ def filter_random(min_value = -10, if len(candidates) == 0: raise OverflowError("There is no candidates for this range and those conditions") - return choice(candidates) + return random.choice(candidates) class FilterRandom(object): @@ -110,7 +159,7 @@ class FilterRandom(object): def __call__(self, min_value=-10, max_value=10): """ Randomly choose on candidate """ self.add_candidates(min_value, max_value) - return choice(self.candidates(min_value, max_value)) + return random.choice(self.candidates(min_value, max_value)) # -----------------------------