Skip to content

Commit 7f882c8

Browse files
authored
Itertool recipe additions (gh-127483)
1 parent 0f91078 commit 7f882c8

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Doc/library/itertools.rst

+37
Original file line numberDiff line numberDiff line change
@@ -877,6 +877,11 @@ and :term:`generators <generator>` which incur interpreter overhead.
877877
"Returns the sequence elements n times."
878878
return chain.from_iterable(repeat(tuple(iterable), n))
879879

880+
def loops(n):
881+
"Loop n times. Like range(n) but without creating integers."
882+
# for _ in loops(100): ...
883+
return repeat(None, n)
884+
880885
def tail(n, iterable):
881886
"Return an iterator over the last n items."
882887
# tail(3, 'ABCDEFG') → E F G
@@ -1099,6 +1104,11 @@ The following recipes have a more mathematical flavor:
10991104
data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p)))
11001105
yield from iter_index(data, 1, start=3)
11011106

1107+
def is_prime(n):
1108+
"Return True if n is prime."
1109+
# is_prime(1_000_000_000_000_403) → True
1110+
return n > 1 and all(n % p for p in sieve(math.isqrt(n) + 1))
1111+
11021112
def factor(n):
11031113
"Prime factors of n."
11041114
# factor(99) → 3 3 11
@@ -1202,6 +1212,16 @@ The following recipes have a more mathematical flavor:
12021212
[0, 2, 4, 6]
12031213

12041214

1215+
>>> for _ in loops(5):
1216+
... print('hi')
1217+
...
1218+
hi
1219+
hi
1220+
hi
1221+
hi
1222+
hi
1223+
1224+
12051225
>>> list(tail(3, 'ABCDEFG'))
12061226
['E', 'F', 'G']
12071227
>>> # Verify the input is consumed greedily
@@ -1475,6 +1495,23 @@ The following recipes have a more mathematical flavor:
14751495
True
14761496

14771497

1498+
>>> 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]
1499+
>>> list(filter(is_prime, range(-100, 100))) == small_primes
1500+
True
1501+
>>> carmichael = {561, 1105, 1729, 2465, 2821, 6601, 8911} # https://oeis.org/A002997
1502+
>>> any(map(is_prime, carmichael))
1503+
False
1504+
>>> # https://www.wolframalpha.com/input?i=is+128884753939+prime
1505+
>>> is_prime(128_884_753_939) # large prime
1506+
True
1507+
>>> is_prime(999953 * 999983) # large semiprime
1508+
False
1509+
>>> is_prime(1_000_000_000_000_007) # factor() example
1510+
False
1511+
>>> is_prime(1_000_000_000_000_403) # factor() example
1512+
True
1513+
1514+
14781515
>>> list(factor(99)) # Code example 1
14791516
[3, 3, 11]
14801517
>>> list(factor(1_000_000_000_000_007)) # Code example 2

0 commit comments

Comments
 (0)