@@ -749,6 +749,11 @@ which incur interpreter overhead.
749
749
750
750
.. testcode ::
751
751
752
+ import collections
753
+ import math
754
+ import operator
755
+ import random
756
+
752
757
def take(n, iterable):
753
758
"Return first n items of the iterable as a list"
754
759
return list(islice(iterable, n))
@@ -853,6 +858,21 @@ which incur interpreter overhead.
853
858
data[2] = 1
854
859
return iter_index(data, 1) if n > 2 else iter([])
855
860
861
+ def factor(n):
862
+ "Prime factors of n."
863
+ # factor(97) --> 97
864
+ # factor(98) --> 2 7 7
865
+ # factor(99) --> 3 3 11
866
+ for prime in sieve(n+1):
867
+ while True:
868
+ quotient, remainder = divmod(n, prime)
869
+ if remainder:
870
+ break
871
+ yield prime
872
+ n = quotient
873
+ if n == 1:
874
+ return
875
+
856
876
def flatten(list_of_lists):
857
877
"Flatten one level of nesting"
858
878
return chain.from_iterable(list_of_lists)
@@ -1104,11 +1124,6 @@ which incur interpreter overhead.
1104
1124
1105
1125
Now, we test all of the itertool recipes
1106
1126
1107
- >>> import operator
1108
- >>> import collections
1109
- >>> import math
1110
- >>> import random
1111
-
1112
1127
>>> take(10 , count())
1113
1128
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1114
1129
@@ -1221,6 +1236,35 @@ which incur interpreter overhead.
1221
1236
>>> set (sieve(10_000 )).isdisjoint(carmichael)
1222
1237
True
1223
1238
1239
+ list(factor(0))
1240
+ []
1241
+ list(factor(1))
1242
+ []
1243
+ list(factor(2))
1244
+ [2]
1245
+ list(factor(3))
1246
+ [3]
1247
+ list(factor(4))
1248
+ [2, 2]
1249
+ list(factor(5))
1250
+ [5]
1251
+ list(factor(6))
1252
+ [2, 3]
1253
+ list(factor(7))
1254
+ [7]
1255
+ list(factor(8))
1256
+ [2, 2, 2]
1257
+ list(factor(9))
1258
+ [3, 3]
1259
+ list(factor(10))
1260
+ [2, 5]
1261
+ all(math.prod(factor(n)) == n for n in range(1, 1000))
1262
+ True
1263
+ all(set(factor(n)) <= set(sieve(n+1)) for n in range(1, 1000))
1264
+ True
1265
+ all(list(factor(n)) == sorted(factor(n)) for n in range(1, 1000))
1266
+ True
1267
+
1224
1268
>>> list (flatten([(' a' , ' b' ), (), (' c' , ' d' , ' e' ), (' f' ,), (' g' , ' h' , ' i' )]))
1225
1269
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
1226
1270
0 commit comments