# pydemo2.py David MacQuigg ece175 5/2/08 '''Python demo2 program More cool stuff. ~ ''' # Recursion and automatic conversion to long integer for large results # def factorial(n): '''Returns an integer n factorial, a long integer if > (2**31 - 1). >>> factorial(13) 6227020800L ''' if n<=1: return 1 return n * factorial(n-1) # List comprehensions are elegant (think of set notation). # def factors(n): '''Return a list of positive integers x <= n, such that n is divisible by x. >>> factors(1000) [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000] ''' return [x for x in range(1, n+1) if n%x==0] def isprime(n): '''Return True if n has only two factors. >>> isprime(17) True ''' return len(factors(n)) == 2 # len is a built-in function def primes(a, b): '''Return a list of prime numbers in range(a, b+1) >>> primes(100, 200) [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, \ 167, 173, 179, 181, 191, 193, 197, 199] ''' return [n for n in range(a, b+1) if isprime(n)] # You can always "unroll" a list conprehension: # def primes_rev1(a, b): result = [] # an empty list for n in range(a, b+1): if isprime(n): result.append(n) return result ### # if __name__ == '__main__': from doctest import testmod testmod(verbose=True)