Efficiency is not considered, just for simplicity.
# Question 2: Use filter to select the prime number within 100 # filter (function or none, sequence)-> list, tuple, or string # filter (def1, list) -> list is 2 to 100. What should this def do? A Boolean function def isprime (m) is returned ): # prime number refers to the number that can only be divisible by 1 and itself for I in range (2, M/2 + 1): If M % I = 0: return false return trueif _ name _ = '_ main _': Print filter (isprime, range (2,101) # isprime is also a number for iterative input, the output is a boolean type, which allows him to return a list, and then go to not. # isprime = Lambda (X: [x % I = 0 for I in range (2, x)]) No # still use the list to parse 2 to the number in the X-1 to determine # [x % I for I in range (2, X) if X % I = 0] Is it possible for each I to divide X? If is a filter condition, and if there is a returned list, there is a number to remove X, the prime number should return a [] isprime = Lambda X: Not [x % I for I in range (2, X) if X % I = 0] # the final formula is prime = filter (lambda X: Not [x % I for I in range (2, X) if X % I = 0], range (2,101) print prime print 'the number of primes is ', Len (PRIME)
You can directly copy and run it. The idea is to simplify it step by step. The usage of generators, reduce, and map is not very familiar, so anonymous functions are used a little more.