Perfect numbers: Difference between revisions
Content deleted Content added
→Functional (faster version): Updated primitives, tidied. |
|||
Line 2,330:
Or, about 20X faster, as measured by ''time.time()'':
<lang python>
from math import (sqrt)▼
from itertools import chain
# main :: IO ()▼
def main():▼
print(▼
list(filter(perfect, enumFromTo(1)(10000)))▼
)▼
# perfect :: Int - > Bool
def perfect(n):
'''Is n the sum of its proper divisors other than 1 ?'''
lows = list(filter(▼
lambda x: 0 == (n % x),▼
# p :: Int -> Bool
enumFromTo(1)(int(sqrt(n)))▼
def p(x)
lows + concatMap(▼
# f :: Int ->
def f(x):
lambda y=(n / x): [y] if x != y else []▼
'''x -> [] if x is the
otherwise
return 1 < n and (
▲ )
▲# main :: IO ()
▲def main():
'''Test'''
▲ print(
))
)
# 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(
Line 2,371 ⟶ 2,386:
# enumFromTo :: (Int
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
|