Home  >  Article  >  Backend Development  >  An example introduction to Yang Hui's triangle method in Python

An example introduction to Yang Hui's triangle method in Python

零下一度
零下一度Original
2017-07-27 09:26:022311browse

Program output needs to achieve the following effects:

[1]
[1,1]
[1,2,1]
[1,3,3,1]

......

Method: iteration, generator

def triangles()
    L = [1]
    while True:
        yiled L
        L =[1] + [L[i] + L[I+1] for i in range(len(L)-1)] + [1]
n = 0
for t in triangles():
    print(t)
    n += 1
    if n == 10:
        break

Implementation logic:

1. Since yield is the generator interrupt output, the first output is [1]

2. Continue the loop after yield under while. At this time, the list length is 1, substitute it len(L) in L, the result is [L[i]+L[i+1] for i in range(1-1)], which is a null value, so the output of yield L is [1,1]

3. At this time, the value of len(L) is 2, and substitution results in [L[i]+L[i+1] for i in range(2-1)] as [L[i]+L[ i+1] for i in range(1)], i can take the value 0, and after substitution, it is [L[0]+L[1]], and the values ​​of L[0] and L[1] are both 1 (It can be seen from the above results), so the output result is [1,2,1]

4. From the third article, it can be seen that the value of len(L) is 3 at this time, and substitution gives [L[i]+ L[i+1] for i in range(2)], the value of i is 0 and 1, and there are two values ​​output through the loop, both are 3, respectively represented by [L[0]+L[1]],[ L[1]+L[2]]

The above is the detailed content of An example introduction to Yang Hui's triangle method in Python. 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