From e500068e45b25ba63f42efb6cf60f8049cc78211 Mon Sep 17 00:00:00 2001 From: Shay Nehmad Date: Sun, 11 Aug 2019 11:43:12 +0300 Subject: [PATCH] Added utility function for calculating power set --- monkey/common/utils/itertools_extensions.py | 9 +++++++++ monkey/common/utils/test_power_set.py | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 monkey/common/utils/itertools_extensions.py create mode 100644 monkey/common/utils/test_power_set.py diff --git a/monkey/common/utils/itertools_extensions.py b/monkey/common/utils/itertools_extensions.py new file mode 100644 index 000000000..b806a659b --- /dev/null +++ b/monkey/common/utils/itertools_extensions.py @@ -0,0 +1,9 @@ +from itertools import chain, combinations + + +def power_set(iterable): + """ + https://docs.python.org/3/library/itertools.html#itertools-recipes + """ + s = list(iterable) + return chain.from_iterable(combinations(s, r) for r in range(1, len(s) + 1)) \ No newline at end of file diff --git a/monkey/common/utils/test_power_set.py b/monkey/common/utils/test_power_set.py new file mode 100644 index 000000000..9c5798327 --- /dev/null +++ b/monkey/common/utils/test_power_set.py @@ -0,0 +1,18 @@ +from unittest import TestCase + + +class TestPower_set(TestCase): + def test_power_set(self): + before = ('a', 'b', 'c') + after_expected = [ + ('a', ), + ('b',), + ('c',), + ('a', 'b'), + ('a', 'c'), + ('b', 'c'), + ('a', 'b', 'c'), + ] + + from common.utils.itertools_extensions import power_set + self.assertEquals(list(power_set(before)), after_expected)