Python simple code implementation example code of Yang Hui triangle, python Yang Hui

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.