@@ -788,6 +788,11 @@ which incur interpreter overhead.
788
788
789
789
.. testcode ::
790
790
791
+ import collections
792
+ import math
793
+ import operator
794
+ import random
795
+
791
796
def take(n, iterable):
792
797
"Return first n items of the iterable as a list"
793
798
return list(islice(iterable, n))
@@ -892,6 +897,21 @@ which incur interpreter overhead.
892
897
data[2] = 1
893
898
return iter_index(data, 1) if n > 2 else iter([])
894
899
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
+
895
915
def flatten(list_of_lists):
896
916
"Flatten one level of nesting"
897
917
return chain.from_iterable(list_of_lists)
@@ -1134,11 +1154,6 @@ which incur interpreter overhead.
1134
1154
1135
1155
Now, we test all of the itertool recipes
1136
1156
1137
- >>> import operator
1138
- >>> import collections
1139
- >>> import math
1140
- >>> import random
1141
-
1142
1157
>>> take(10 , count())
1143
1158
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1144
1159
@@ -1251,6 +1266,35 @@ which incur interpreter overhead.
1251
1266
>>> set (sieve(10_000 )).isdisjoint(carmichael)
1252
1267
True
1253
1268
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
+
1254
1298
>>> list (flatten([(' a' , ' b' ), (), (' c' , ' d' , ' e' ), (' f' ,), (' g' , ' h' , ' i' )]))
1255
1299
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
1256
1300
0 commit comments