@@ -788,6 +788,11 @@ which incur interpreter overhead.
788788
789789..testcode ::
790790
791+ import collections
792+ import math
793+ import operator
794+ import random
795+
791796 def take(n, iterable):
792797 "Return first n items of the iterable as a list"
793798 return list(islice(iterable, n))
@@ -892,6 +897,21 @@ which incur interpreter overhead.
892897 data[2] = 1
893898 return iter_index(data, 1) if n > 2 else iter([])
894899
900+ def factor(n):
901+ "Prime factors of n."
902+ # factor(97) --> 97
903+ # factor(98) --> 2 7 7
904+ # factor(99) --> 3 3 11
905+ for prime in sieve(n+1):
906+ while True:
907+ quotient, remainder = divmod(n, prime)
908+ if remainder:
909+ break
910+ yield prime
911+ n = quotient
912+ if n == 1:
913+ return
914+
895915 def flatten(list_of_lists):
896916 "Flatten one level of nesting"
897917 return chain.from_iterable(list_of_lists)
@@ -1134,11 +1154,6 @@ which incur interpreter overhead.
11341154
11351155 Now, we test all of the itertool recipes
11361156
1137- >>>import operator
1138- >>>import collections
1139- >>>import math
1140- >>>import random
1141-
11421157 >>>take(10 , count())
11431158[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
11441159
@@ -1251,6 +1266,35 @@ which incur interpreter overhead.
12511266 >>>set (sieve(10_000 )).isdisjoint(carmichael)
12521267True
12531268
1269+ list(factor(0))
1270+ []
1271+ list(factor(1))
1272+ []
1273+ list(factor(2))
1274+ [2]
1275+ list(factor(3))
1276+ [3]
1277+ list(factor(4))
1278+ [2, 2]
1279+ list(factor(5))
1280+ [5]
1281+ list(factor(6))
1282+ [2, 3]
1283+ list(factor(7))
1284+ [7]
1285+ list(factor(8))
1286+ [2, 2, 2]
1287+ list(factor(9))
1288+ [3, 3]
1289+ list(factor(10))
1290+ [2, 5]
1291+ all(math.prod(factor(n)) == n for n in range(1, 1000))
1292+ True
1293+ all(set(factor(n)) <= set(sieve(n+1)) for n in range(1, 1000))
1294+ True
1295+ all(list(factor(n)) == sorted(factor(n)) for n in range(1, 1000))
1296+ True
1297+
12541298 >>>list (flatten([(' a' ,' b' ), (), (' c' ,' d' ,' e' ), (' f' ,), (' g' ,' h' ,' i' )]))
12551299['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
12561300