Today, I saw the Python tutorial generator on the website of Liao Xuefeng, and did a little exercise in the Yang Hui's triangle. The requirement is to write a generator that can be iterated to print out each row of the Yang Hui's triangle.
The basic idea is to generate the initial situation, and then every time you follow the Yang Hui's triangle's calculation rules to update the list to remove the middle and end. Because calculating the value of each item depends on the result of the previous item, you cannot update the value directly in the original list as you would fib a series, and you need to store a new row value with a temporary list and replace it with the original list. The code is as follows:
def triangles ():
L = [1]
n = 0 while
1:
yield L
l.append (1)
temp = [] for
I,item in enumerate ( L[:-2]):
temp.append (l[i]+l[i+1])
l[1:-1] = Temp
In fact, the for loop in the above code is essentially generating a temp list, so you can also use list generation in Python to further simplify the above code:
def triangles ():
L = [1]
n = 0 while
1:
yield L
l.append (1)
l[1:-1] = [item+l[i+1] for I,it EM in Enumerate (L[:-2])]
I have to say, Python can really write very concise code, many C + + Java need to write a lot of loops to do things, Python one line of code is done ~