Perfect numbers: Difference between revisions

Content deleted Content added
Hout (talk | contribs)
Hout (talk | contribs)
→‎Functional Python (faster version): A simplification, with one less import.
Line 2,330:
 
 
Or, aboutover 20X faster, as measured by ''time.time()'':
 
<lang python>'''Perfect numbers'''
 
from itertools import chain
from math import sqrt
 
Line 2,347 ⟶ 2,346:
return 0 == (n % x)
 
#root f= :: Int -> [Int]sqrt(n)
lows = list(filter(p, enumFromTo(1)(int(sqrt(n)root))))
def f(x):
'''x -> [] if x is the square root of n,
otherwise x -> [cofactor of x]'''
y = n / x
return [y] if x != y else []
 
lows = list(filter(p, enumFromTo(1)(int(sqrt(n)))))
return 1 < n and (
n == sum(lows + concatMap(f)([n / x for x in lows) if root != x]) / 2
)
 
Line 2,372 ⟶ 2,365:
 
# GENERIC -------------------------------------------------
 
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''Concatenated list over which a function has been mapped.
The list monad can be derived by using a function f which
wraps its output a in list,
(using an empty list to represent computational failure).'''
return lambda xs: list(
chain.from_iterable(
map(f, xs)
)
)
 
 
# enumFromTo :: (Int, Int) -> [Int]