summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2024-12-04 00:20:01 (GMT)
committerGitHub <noreply@github.com>2024-12-04 00:20:01 (GMT)
commit7f882c88cfda486947974cb82c20a1ae7047edfc (patch)
tree9bd0fc01d2284da6f47984910d4a0dd33d38ac7c /Doc
parent0f9107817022f0defac157e3795a4093a32ea320 (diff)
downloadcpython-7f882c88cfda486947974cb82c20a1ae7047edfc.zip
cpython-7f882c88cfda486947974cb82c20a1ae7047edfc.tar.gz
cpython-7f882c88cfda486947974cb82c20a1ae7047edfc.tar.bz2
Itertool recipe additions (gh-127483)
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/itertools.rst37
1 files changed, 37 insertions, 0 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index c138e90..03966f3 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -877,6 +877,11 @@ and :term:`generators <generator>` which incur interpreter overhead.
"Returns the sequence elements n times."
return chain.from_iterable(repeat(tuple(iterable), n))
+ def loops(n):
+ "Loop n times. Like range(n) but without creating integers."
+ # for _ in loops(100): ...
+ return repeat(None, n)
+
def tail(n, iterable):
"Return an iterator over the last n items."
# tail(3, 'ABCDEFG') → E F G
@@ -1099,6 +1104,11 @@ 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
@@ -1202,6 +1212,16 @@ The following recipes have a more mathematical flavor:
[0, 2, 4, 6]
+ >>> for _ in loops(5):
+ ... print('hi')
+ ...
+ hi
+ hi
+ hi
+ hi
+ hi
+
+
>>> list(tail(3, 'ABCDEFG'))
['E', 'F', 'G']
>>> # Verify the input is consumed greedily
@@ -1475,6 +1495,23 @@ The following recipes have a more mathematical flavor:
True
+ >>> small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
+ >>> list(filter(is_prime, range(-100, 100))) == small_primes
+ True
+ >>> carmichael = {561, 1105, 1729, 2465, 2821, 6601, 8911} # https://oeis.org/A002997
+ >>> any(map(is_prime, carmichael))
+ False
+ >>> # https://www.wolframalpha.com/input?i=is+128884753939+prime
+ >>> is_prime(128_884_753_939) # large prime
+ True
+ >>> is_prime(999953 * 999983) # large semiprime
+ False
+ >>> is_prime(1_000_000_000_000_007) # factor() example
+ False
+ >>> is_prime(1_000_000_000_000_403) # factor() example
+ True
+
+
>>> list(factor(99)) # Code example 1
[3, 3, 11]
>>> list(factor(1_000_000_000_000_007)) # Code example 2