[Python] Calculation of prime numbers less than 100-one row of code Filter Method

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.