Perfect numbers: Difference between revisions
Content added Content deleted
(→Functional (faster version): Updated primitives, tidied.) |
|||
Line 2,330: | Line 2,330: | ||
Or, about 20X faster, as measured by ''time.time()'': |
|||
Or, an order of magnitude faster (by restricting the search space): |
|||
<lang python> |
<lang python>'''Perfect numbers''' |
||
⚫ | |||
from itertools import chain |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
# perfect :: Int - > Bool |
# perfect :: Int - > Bool |
||
def perfect(n): |
def perfect(n): |
||
'''Is n the sum of its proper divisors other than 1 ?''' |
|||
⚫ | |||
⚫ | |||
# p :: Int -> Bool |
|||
⚫ | |||
) |
def p(x): |
||
'Factor of n.' |
|||
return 0 == (n % x) |
|||
⚫ | |||
# f :: Int -> [Int] |
|||
def f(x): |
|||
⚫ | |||
'''x -> [] if x is the square root of n, |
|||
otherwise x -> [cofactor of x]''' |
|||
y = n / x |
|||
⚫ | |||
⚫ | |||
return 1 < n and ( |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
'''Test''' |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
)) |
|||
) |
) |
||
# GENERIC -------------------------------- |
# GENERIC ------------------------------------------------- |
||
# concatMap :: (a -> [b]) -> [a] -> [b] |
# concatMap :: (a -> [b]) -> [a] -> [b] |
||
def concatMap(f): |
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( |
return lambda xs: list( |
||
chain.from_iterable( |
chain.from_iterable( |
||
Line 2,371: | Line 2,386: | ||
# enumFromTo :: Int |
# enumFromTo :: (Int, Int) -> [Int] |
||
def enumFromTo(m): |
def enumFromTo(m): |
||
'''Integer enumeration from m to n.''' |
|||
return lambda n: list(range(m, 1 + n)) |
return lambda n: list(range(m, 1 + n)) |
||