@@ -877,6 +877,11 @@ and :term:`generators <generator>` which incur interpreter overhead.
877
877
"Returns the sequence elements n times."
878
878
return chain.from_iterable(repeat(tuple(iterable), n))
879
879
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
+
880
885
def tail(n, iterable):
881
886
"Return an iterator over the last n items."
882
887
# tail(3, 'ABCDEFG') → E F G
@@ -1099,6 +1104,11 @@ The following recipes have a more mathematical flavor:
1099
1104
data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p)))
1100
1105
yield from iter_index(data, 1, start=3)
1101
1106
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
+
1102
1112
def factor(n):
1103
1113
"Prime factors of n."
1104
1114
# factor(99) → 3 3 11
@@ -1202,6 +1212,16 @@ The following recipes have a more mathematical flavor:
1202
1212
[0, 2, 4, 6]
1203
1213
1204
1214
1215
+ >>> for _ in loops(5 ):
1216
+ ... print (' hi' )
1217
+ ...
1218
+ hi
1219
+ hi
1220
+ hi
1221
+ hi
1222
+ hi
1223
+
1224
+
1205
1225
>>> list (tail(3 , ' ABCDEFG' ))
1206
1226
['E', 'F', 'G']
1207
1227
>>> # Verify the input is consumed greedily
@@ -1475,6 +1495,23 @@ The following recipes have a more mathematical flavor:
1475
1495
True
1476
1496
1477
1497
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
+
1478
1515
>>> list (factor(99 )) # Code example 1
1479
1516
[3, 3, 11]
1480
1517
>>> list (factor(1_000_000_000_000_007 )) # Code example 2
0 commit comments