Home  >  Article  >  Backend Development  >  How to express the number of daffodils in python code?

How to express the number of daffodils in python code?

coldplay.xixi
coldplay.xixiOriginal
2020-06-23 16:22:3913479browse

How to express the number of daffodils in python code?

How to express the number of daffodils using python code?

The python code of the narcissus number is:

The daffodil number refers to a 3-digit positive integer, and the number in each digit of it is 3 The sum of powers is equal to itself. (For example: 1^3 5^3 3^3 = 153)

The following code is used to find the number of all daffodils:

>>> 
>>> 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]
>>>

Instructions:

Above The code can be decomposed 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))

The first line means using a list to push through all three digits, and mark each number. If it is a daffodil, it will be marked True, if it is not, it will be marked False. Flags and numbers are placed into a tuple: (flag, value), and all tuples are placed into a list structure.

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

The third sentence means to put the second value of the tuple filtered out by the first sentence into the list structure.

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

Recommended tutorial: "Python Video Tutorial"

The above is the detailed content of How to express the number of daffodils in python code?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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