mirror of
https://github.com/python/cpython.git
synced 2025-10-03 21:55:41 +00:00
Improve factor() recipe and fix its tests (GH-100576)
(cherry picked from commit 2d52406835
)
Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
This commit is contained in:
parent
de621281ce
commit
95fa61cbce
1 changed files with 20 additions and 20 deletions
|
@ -860,18 +860,16 @@ which incur interpreter overhead.
|
||||||
|
|
||||||
def factor(n):
|
def factor(n):
|
||||||
"Prime factors of n."
|
"Prime factors of n."
|
||||||
# factor(97) --> 97
|
|
||||||
# factor(98) --> 2 7 7
|
|
||||||
# factor(99) --> 3 3 11
|
# factor(99) --> 3 3 11
|
||||||
for prime in sieve(n+1):
|
for prime in sieve(math.isqrt(n) + 1):
|
||||||
while True:
|
while n >= prime:
|
||||||
quotient, remainder = divmod(n, prime)
|
quotient, remainder = divmod(n, prime)
|
||||||
if remainder:
|
if remainder:
|
||||||
break
|
break
|
||||||
yield prime
|
yield prime
|
||||||
n = quotient
|
n = quotient
|
||||||
if n == 1:
|
if n >= 2:
|
||||||
return
|
yield n
|
||||||
|
|
||||||
def flatten(list_of_lists):
|
def flatten(list_of_lists):
|
||||||
"Flatten one level of nesting"
|
"Flatten one level of nesting"
|
||||||
|
@ -1236,33 +1234,35 @@ which incur interpreter overhead.
|
||||||
>>> set(sieve(10_000)).isdisjoint(carmichael)
|
>>> set(sieve(10_000)).isdisjoint(carmichael)
|
||||||
True
|
True
|
||||||
|
|
||||||
list(factor(0))
|
>>> list(factor(0))
|
||||||
[]
|
[]
|
||||||
list(factor(1))
|
>>> list(factor(1))
|
||||||
[]
|
[]
|
||||||
list(factor(2))
|
>>> list(factor(2))
|
||||||
[2]
|
[2]
|
||||||
list(factor(3))
|
>>> list(factor(3))
|
||||||
[3]
|
[3]
|
||||||
list(factor(4))
|
>>> list(factor(4))
|
||||||
[2, 2]
|
[2, 2]
|
||||||
list(factor(5))
|
>>> list(factor(5))
|
||||||
[5]
|
[5]
|
||||||
list(factor(6))
|
>>> list(factor(6))
|
||||||
[2, 3]
|
[2, 3]
|
||||||
list(factor(7))
|
>>> list(factor(7))
|
||||||
[7]
|
[7]
|
||||||
list(factor(8))
|
>>> list(factor(8))
|
||||||
[2, 2, 2]
|
[2, 2, 2]
|
||||||
list(factor(9))
|
>>> list(factor(9))
|
||||||
[3, 3]
|
[3, 3]
|
||||||
list(factor(10))
|
>>> list(factor(10))
|
||||||
[2, 5]
|
[2, 5]
|
||||||
all(math.prod(factor(n)) == n for n in range(1, 1000))
|
>>> list(factor(999953*999983))
|
||||||
|
[999953, 999983]
|
||||||
|
>>> all(math.prod(factor(n)) == n for n in range(1, 1000))
|
||||||
True
|
True
|
||||||
all(set(factor(n)) <= set(sieve(n+1)) for n in range(1, 1000))
|
>>> all(set(factor(n)) <= set(sieve(n+1)) for n in range(1, 1000))
|
||||||
True
|
True
|
||||||
all(list(factor(n)) == sorted(factor(n)) for n in range(1, 1000))
|
>>> all(list(factor(n)) == sorted(factor(n)) for n in range(1, 1000))
|
||||||
True
|
True
|
||||||
|
|
||||||
>>> list(flatten([('a', 'b'), (), ('c', 'd', 'e'), ('f',), ('g', 'h', 'i')]))
|
>>> list(flatten([('a', 'b'), (), ('c', 'd', 'e'), ('f',), ('g', 'h', 'i')]))
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue