[Tutor] primality testing

Magnus Lyckå magnus@thinkware.se
Fri May 9 22:30:02 2003


At 13:58 2003-05-09 -0700, Zak Arntson wrote:
>def prime (n):
>         if 0 not in map (lambda a: n % a, range (2, math.sqrt (n) + 1)):
>                 return 'p'
>         return 'c'

Please don't put a space between a function name and the (.
See http://www.python.org/peps/pep-0008.html

A more "modern" approach is to use list comprehension instead
of map and lambda.

Also, if we have an expression that returns 0 or 1, we can use
these numbers as index in a sequence instead of using an if
statement.

def prime(n):
     return ['prime', 'comp'][0 in
        [n % a for a in range(2, math.sqrt (n) + 1)]]



--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program