How to implement Yang Hui triangle in python (code)

不言
Release: 2018-08-30 09:33:33
Original
11990 people have browsed it

The content of this article is about how to implement Yang Hui's triangle (code) in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Yang Hui triangle Yang Hui is defined as follows:

         1
        / \
       1   1
      / \ / \
     1   2   1
    / \ / \ / \
   1   3   3   1
  / \ / \ / \ / \
  1   4   6   4   1
 / \ / \ / \ / \ / \
1   5   10  10  5   1
Copy after login

Consider each line as a list, try to write a generator, and continuously output the list of the next line:

def triangles():
    L = [1]
    while True:
        yield L
        
        M=L[:]#复制一个list,这样才不会影响到原有的list。不然results里的每个列表的末尾会为0.
        M.append(0)
        L = [M[i-1]+M[i] for i in range(len(M))] 
        
n =0
results = []
for t in triangles():
    
    print(t)
    results.append(t)
    print(results)
    n = n +1
    if n == 10:
        break
Copy after login

Related recommendations:

Use Python to output an example of Yang Hui's triangle

Write the Yang Hui triangle example code in PHP_PHP

The above is the detailed content of How to implement Yang Hui triangle in python (code). 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!