From f035b942b412a1e831b3c5a619d1920b396a7daf Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Wed, 11 Dec 2024 20:50:36 -0600 Subject: [PATCH 1/3] Simpler and faster is_prime() recipe. --- Doc/library/itertools.rst | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 03966f3d3d694b..01b1ac7d184c8f 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -1104,11 +1104,6 @@ The following recipes have a more mathematical flavor: data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p))) yield from iter_index(data, 1, start=3) - def is_prime(n): - "Return True if n is prime." - # is_prime(1_000_000_000_000_403) → True - return n > 1 and all(n % p for p in sieve(math.isqrt(n) + 1)) - def factor(n): "Prime factors of n." # factor(99) → 3 3 11 @@ -1123,6 +1118,10 @@ The following recipes have a more mathematical flavor: if n > 1: yield n + def is_prime(n): + "Return True if n is prime." + return n > 1 and next(factor(n)) == n + def totient(n): "Count of natural numbers up to n that are coprime to n." # https://mathworld.wolfram.com/TotientFunction.html From 6d2b0dbc3e4664963e364416f9a6a9b3ae213abf Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Wed, 11 Dec 2024 20:52:05 -0600 Subject: [PATCH 2/3] Consistent commenting --- Doc/library/itertools.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 01b1ac7d184c8f..26913e7512224d 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -1015,7 +1015,7 @@ The following recipes have a more mathematical flavor: .. testcode:: def powerset(iterable): - "powerset([1,2,3]) → () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" + # powerset([1,2,3]) → () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) From 8c161f1ffac0115aa9f2c0d5ba2bd6120c71ee6f Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Wed, 11 Dec 2024 21:16:18 -0600 Subject: [PATCH 3/3] Include original example --- Doc/library/itertools.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 26913e7512224d..3b90d7830f3681 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -1120,6 +1120,7 @@ The following recipes have a more mathematical flavor: def is_prime(n): "Return True if n is prime." + # is_prime(1_000_000_000_000_403) → True return n > 1 and next(factor(n)) == n def totient(n):