Skip to content

Commit 78359b1

Browse files
authored
Simplify sieve() recipe. Add edge case tests. (GH-96892)
1 parent 0587810 commit 78359b1

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

Doc/library/itertools.rst

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -818,7 +818,7 @@ which incur interpreter overhead.
818818
data = bytearray([1]) * n
819819
data[:2] = 0, 0
820820
limit = math.isqrt(n) + 1
821-
for p in compress(count(), islice(data, limit)):
821+
for p in compress(range(limit), data):
822822
data[p+p : n : p] = bytearray(len(range(p+p, n, p)))
823823
return compress(count(), data)
824824

@@ -1168,6 +1168,9 @@ which incur interpreter overhead.
11681168

11691169
>>> list(sieve(30))
11701170
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
1171+
>>> small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59]
1172+
>>> all(list(sieve(n)) == [p for p in small_primes if p < n] for n in range(60))
1173+
True
11711174
>>> len(list(sieve(100)))
11721175
25
11731176
>>> len(list(sieve(1_000)))
@@ -1178,6 +1181,9 @@ which incur interpreter overhead.
11781181
9592
11791182
>>> len(list(sieve(1_000_000)))
11801183
78498
1184+
>>> carmichael = {561, 1105, 1729, 2465, 2821, 6601, 8911} # https://oeis.org/A002997
1185+
>>> set(sieve(10_000)).isdisjoint(carmichael)
1186+
True
11811187

11821188
>>> list(flatten([('a', 'b'), (), ('c', 'd', 'e'), ('f',), ('g', 'h', 'i')]))
11831189
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

0 commit comments

Comments
 (0)