An example of the Python Yang Hui triangle method

Source: Internet
Author: User
Program output requires the following effects:

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

......

Method: Iteration, generator

def triangles ()    L = [1] While    True:        yiled L        =[1] + [l[i] + l[i+1] for I in range (len (L)-1)] + [1]n = 0fo R T in triangles ():    print (t)    n + = 1    if n = = Ten:        break

Implementation logic:

1. Since yield interrupts the output for the generator, it has the first output as [1]

2. Continue with the after yield loop, at which time the list length is 1, substituting it into the Len (L) in L, the [l[i]+l[i+1] for I in range (1-1)] is drawn as null, so the yield L output as [MAX]

3. At this time Len (L) value is 2, substituting [l[i]+l[i+1] for I in range (2-1)] is [l[i]+l[i+1] for I in range (1)],i can be evaluated as 0, substituting for [l[0]+l[1]], and l[0] and l[1] Has a value of 1 (as shown above), so the output is [1,2,1]

4. From the third article, The Len (L) value is 3, substituting [l[i]+l[i+1] for I in range (2)],i value 0 and 1, through the loop output has two values, all 3, respectively by [L[0]+l[1]],[l[1]+l[2]]

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.