Home > Backend Development > Python Tutorial > Python code how to find the number of all daffodils

Python code how to find the number of all daffodils

coldplay.xixi
Release: 2020-08-12 14:57:02
Original
8207 people have browsed it

Python code to find all daffodil numbers: first use the list to push through all three-digit numbers, and mark each number; then filter out the tuples marked as True; and finally the first sentence Put the second value of the filtered tuple into the list structure and add a print statement.

Python code how to find the number of all daffodils

Python code to find the number of all daffodils:

Method one:

>>> 
>>> a = list(map(lambda x: x[1], filter(lambda x: x[0], [(i*100+j*10+k == i**3+j**3+k**3, i**3+j**3+k**3) for i in range(1, 10) for j in range(0, 10) for k in range(0, 10)])))
>>> print(a)
[153, 370, 371, 407]
>>>
Copy after login

Related learning recommendations: python video tutorial

Instructions:

The above code can be broken down into three lines of code:

a = [(i*100+j*10+k == i**3+j**3+k**3, i**3+j**3+k**3) for i in range(1, 10) for j in range(0, 10) for k in range(0, 10)]
b = filter(lambda x: x[0], a)
c = list(map(lambda x: x[1], b))
Copy after login

The first sentence means using a list to push through all three digits, and each number is marked. If the daffodils are counting, mark True, if not, mark False. The marks and numbers are put into one ancestor: ( flag, value), all tuples are placed in a list structure.

The second sentence means to filter out the tuples marked as True.

The third sentence means c.

Add the print statement and execute the above three lines of code to understand.

Method 2:

Only use list derivation.

>>> a = [i**3+j**3+k**3 for i in range(1, 10) for j in range(0, 10) for k in range(0, 10) if i*100+j*10+k == i**3+j**3+k**3]
>>> print(a)
[153, 370, 371, 407]
>>>
Copy after login

Related recommendations: Programming video course

The above is the detailed content of Python code how to find the number of all daffodils. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template