Home  >  Article  >  Backend Development  >  Write a python generator to generate a code example of Yang Hui's triangle

Write a python generator to generate a code example of Yang Hui's triangle

Y2J
Y2JOriginal
2017-04-26 11:20:382088browse

The following editor will bring you an article on how to generate Yang Hui triangle with python generator (must read). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Writing interesting programs in Python feels so awesome that I can’t stop.

#生成器生成展示杨辉三角
#原理是在一个2维数组里展示杨辉三角,空的地方用0,输出时,转化为' '
def yang(line):
  n,leng=0,2*line - 1
  f_list = list(range(leng+2)) #预先分配,insert初始胡会拖慢速度,最底下一行,左右也有1个空格
  #全部初始化为0
  for i,v in enumerate(f_list):
    f_list[v] = 0
  ZEROLIST = f_list[:] #预留一个全零的数组
  f_list[leng//2] = 1 #初始的第一行
  re_list =f_list[:]
  n=0
  while n < line:
    n = n+1
    yield re_list
    f_list,re_list = re_list[:],ZEROLIST[:]
    start = leng//2-n #计算一行中第一个1的位置
    end = start + 2*n #计算一行中最后一个1的位置
    while start <= end:
      re_list[start] = f_list[start - 1] + f_list[start+1] #不管是不是1,该位置的数字,都是上一行该位置的左右两个数的和
      start = start + 1
  return &#39;done&#39;

def printList(L):
  n = 0
  p_str = &#39;&#39;
  for value in L:
    ch = str(value)
    if value == 0:
      ch = &#39; &#39;
    p_str = p_str + ch
  print(p_str)

for value in yang(8):
  printList(value)

The above is the detailed content of Write a python generator to generate a code example of Yang Hui's triangle. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn