@@ -829,6 +829,11 @@ and :term:`generators <generator>` which incur interpreter overhead.
829
829
"Returns the sequence elements n times."
830
830
return chain.from_iterable(repeat(tuple(iterable), n))
831
831
832
+ def loops(n):
833
+ "Loop n times. Like range(n) but without creating integers."
834
+ # for _ in loops(100): ...
835
+ return repeat(None, n)
836
+
832
837
def tail(n, iterable):
833
838
"Return an iterator over the last n items."
834
839
# tail(3, 'ABCDEFG') → E F G
@@ -1060,6 +1065,11 @@ The following recipes have a more mathematical flavor:
1060
1065
data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p)))
1061
1066
yield from iter_index(data, 1, start=3)
1062
1067
1068
+ def is_prime(n):
1069
+ "Return True if n is prime."
1070
+ # is_prime(1_000_000_000_000_403) → True
1071
+ return n > 1 and all(n % p for p in sieve(math.isqrt(n) + 1))
1072
+
1063
1073
def factor(n):
1064
1074
"Prime factors of n."
1065
1075
# factor(99) → 3 3 11
@@ -1165,6 +1175,17 @@ The following recipes have a more mathematical flavor:
1165
1175
>>> list (islice(tabulate(lambda x : 2 * x), 4 ))
1166
1176
[0, 2, 4, 6]
1167
1177
1178
+
1179
+ >>> for _ in loops(5 ):
1180
+ ... print (' hi' )
1181
+ ...
1182
+ hi
1183
+ hi
1184
+ hi
1185
+ hi
1186
+ hi
1187
+
1188
+
1168
1189
>>> list (tail(3 , ' ABCDEFG' ))
1169
1190
['E', 'F', 'G']
1170
1191
>>> # Verify the input is consumed greedily
@@ -1424,6 +1445,24 @@ The following recipes have a more mathematical flavor:
1424
1445
>>> set (sieve(10_000 )).isdisjoint(carmichael)
1425
1446
True
1426
1447
1448
+
1449
+ >>> 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 ]
1450
+ >>> list (filter (is_prime, range (- 100 , 100 ))) == small_primes
1451
+ True
1452
+ >>> carmichael = {561 , 1105 , 1729 , 2465 , 2821 , 6601 , 8911 } # https://oeis.org/A002997
1453
+ >>> any (map (is_prime, carmichael))
1454
+ False
1455
+ >>> # https://www.wolframalpha.com/input?i=is+128884753939+prime
1456
+ >>> is_prime(128_884_753_939 ) # large prime
1457
+ True
1458
+ >>> is_prime(999953 * 999983 ) # large semiprime
1459
+ False
1460
+ >>> is_prime(1_000_000_000_000_007 ) # factor() example
1461
+ False
1462
+ >>> is_prime(1_000_000_000_000_403 ) # factor() example
1463
+ True
1464
+
1465
+
1427
1466
>>> list (factor(99 )) # Code example 1
1428
1467
[3, 3, 11]
1429
1468
>>> list (factor(1_000_000_000_000_007 )) # Code example 2
0 commit comments