# python realizes Yang Hui triangle thinking

- 2020-06-12 09:50:29
- OfStack

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 cycle after yield under while, at this time, the length of list is 1, substitute it into len(L) in L, and get [L[i]+L[i+1] for i in range(1-1)], so the output of yield L is [1,1]

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

4. According to article 3, at this time, the value of len(L) is 3, and [L[i]+L[i+1] for i range(2)] is obtained by substitution. The value of i is 0 and 1.

And so on