Python minimalist code implementation Yang Hui's triangle sample code _python

Source: Internet
Author: User
Tags generator generator generator

Yang Hui's triangle, also called Jia Xian triangle, Pascal Triangle, is a geometric arrangement of two-item coefficients in a triangle.

Think of each row as a list, write a generator, and keep outputting the list of the next line

Achieve the following output effects:

# [1] 
# [1, 1] 
# [1, 2, 1] # [1, 3, 
3, 1] 
# [1, 4, 6, 4, 1] 
# [1, 5, ten, 5, 1] # [1, 6 
, 15, 20 , 6, 1] 
# [1, 7, M,, 7, 1] # [1, 8, 28, 56, 70, 56, 
28, 8, 1] 

>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>

Minimalist 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: 
    

Note: the difference between the normal function and the generator generator:

1, the ordinary function call returns the result directly, generator function's call, returns a generator object; (You can create an object when you call generator, and then use the next() method to get the next return value, but in practice it's usually implemented in a for loop)

2, generator in the implementation process, encountered yield interrupted, the next time to continue to implement

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work to bring certain help, if you have questions you can message exchange.

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.