Perfect numbers: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: Added a slightly faster variant)
(→‎{{header|Python}}: replaced reduce(add) with sum)
Line 2,143: Line 2,143:
Or, a little faster (by restricting the search space):
Or, a little faster (by restricting the search space):


<lang python>from functools import (reduce)
<lang python>from operator import (add)
from operator import (add)
from math import (sqrt)
from math import (sqrt)


Line 2,152: Line 2,151:




# perfect:: Int - > Bool
# perfect::Int - > Bool
def perfect(n):
def perfect(n):
lows = filter(
lows = filter(
Line 2,158: Line 2,157:
xrange(1, 1 + int(sqrt(n)))
xrange(1, 1 + int(sqrt(n)))
)
)
return (1 < n) and (n == reduce(
return (1 < n) and(
add,
n == sum(
lows + concatMap(
lows + concatMap(
lambda x: (
lambda x: (
lambda y=n / x: [y] if x != y else []
lambda y=n / x: [y]
)()
if x != y
)(lows), 0) / 2)
else []
)()
)(lows)
) / 2
)




# GENERIC -----------------------------------------
# GENERIC-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -


# concatMap :: (a -> [b]) -> [a] -> [b]
# concatMap::(a - > [b]) - > [a] - > [b]
def concatMap(f):
def concatMap(f):
return lambda xs: (
return lambda xs: (