Python simple code implementation example code of Yang Hui triangle, python Yang Hui
The Yang Hui triangle, also known as the Jia Xian triangle and Pascal triangle, is a geometric arrangement of the binary coefficient in the triangle.
Think of each row as a list, write a generator, and continuously output the list of the next row
Achieve the following output results:
# [1] # [1, 1] # [1, 2, 1] # [1, 3, 3, 1] # [1, 4, 6, 4, 1] # [1, 5, 10, 10, 5, 1] # [1, 6, 15, 20, 15, 6, 1] # [1, 7, 21, 35, 35, 21, 7, 1] # [1, 8, 28, 56, 70, 56, 28, 8, 1] # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Simple code implementation:
def triangles(): L = [1] while True: yield L L.append(0); L = [L[i-1] + L[i] for i in range(len(L))] n = 0 for t in triangles(): print(t) n = n + 1 if n == 10: break
Note:Differences between common functions and generator generators:
1. A normal function call directly returns the result. A generator object is returned when the generator function is called. (You can create an object before calling the generator function.next()
The method continuously obtains the next return value, but is usually implemented by the for loop)
2. generator is interrupted when yield is encountered during execution and will continue to be executed next time.
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.