Python implementation: Yang Hui triangle ideas

Source: Internet
Author: User


The Yang Hui Triangle has several features:

    1. Each number equals two of the sum above it.
    2. Each line of numbers is symmetrical, starting from 1 to become larger.
    3. The number of the nth row has n items.
    4. The nth row number and 2n-1.
    5. The number of m in the nth row can be expressed as C (n-1,m-1), which is the number of combinations of m-1 elements taken from n-1 different elements.
    6. The number of the nth row is equal to the number of n-m+1 and is one of the combinatorial number properties.
            1          1   1        1   2   1      1   3   3   1    1   4   6   4   1  1   5   Ten   5    1    

My idea is that the first line has only one element of 1, so the second line must be 1. So the key is to calculate the number of outputs in the next few lines, first put it into the list.

The first element of the third row table can be known as [2] is the 2nd column of the No. 0 element and the first element of the and, since the No. 0 element has been 1 without it, so there is l[a]=l[a]+l[a+1], the next line is output from the previous line, now the third line

is [to], and then the tail with a [1], you can get the third row, the list length also added one, and so on and so on [1,3,3], and then add [1], Output line fourth, the code is implemented as follows

1 def Yanghui (n): 2     l=[1,1]3      for with range (1, N):4          for inch Range (x): 5             L[a]=l[a]+l[a+1]6         L.insert (0,1)7     return l

Each line will be output in the format later,

Re-unified printing



1 x=int (input ())2 a=13 b=04print((x-a+1) *'  ', [1])5 while a<x:6     b=Yanghui (a)  7     print((x-a) *", b)8     a+=1

Better understanding than the algorithm that needs to use the generator, and some trickery, can be used as a way of thinking



Python implementation: Yang Hui triangle ideas

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.