Python Yang Hui's triangle __python

Source: Internet
Author: User


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 ~

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.