8000 Misc Itertools recipe tweaks (GH-100493) · python/cpython@ba87dae · GitHub
[go: up one dir, main page]

Skip to content

Commit ba87dae

Browse files
Misc Itertools recipe tweaks (GH-100493)
(cherry picked from commit 0769f95) Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
1 parent 57e727a commit ba87dae

File tree

1 file changed

+49
-5
lines changed

1 file changed

+49
-5
lines changed

Doc/library/itertools.rst

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,11 @@ which incur interpreter overhead.
749749

750750
.. testcode::
751751

752+
import collections
753+
import math
754+
import operator
755+
import random
756+
752757
def take(n, iterable):
753758
"Return first n items of the iterable as a list"
754759
return list(islice(iterable, n))
@@ -853,6 +858,21 @@ which incur interpreter overhead.
853858
data[2] = 1
854859
return iter_index(data, 1) if n > 2 else iter([])
855860

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+
856876
def flatten(list_of_lists):
857877
"Flatten one level of nesting"
858878
return chain.from_iterable(list_of_lists)
@@ -1104,11 +1124,6 @@ which incur interpreter overhead.
11041124

11051125
Now, we test all of the itertool recipes
11061126

1107-
>>> import operator
1108-
>>> import collections
1109-
>>> import math
1110-
>>> import random
1111-
11121127
>>> take(10, count())
11131128
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
11141129

@@ -1221,6 +1236,35 @@ which incur interpreter overhead.
12211236
>>> set(sieve(10_000)).isdisjoint(carmichael)
12221237
True
12231238

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+
12241268
>>> list(flatten([('a', 'b'), (), ('c', 'd', 'e'), ('f',), ('g', 'h', 'i')]))
12251269
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
12261270

0 commit comments

Comments
 (0)
0