python generator generates Yang hui triangle method of must see

  • 2020-05-30 20:25:48
  • OfStack

Writing interesting programs with Python feels good and can't stop


# Generator generated display Yang hui 3 Angle 
# Principle is in 1 a 2 The dimension array shows Yang hui 3 Angle, for the empty space 0 When output, is converted to ' '
def yang(line):
  n,leng=0,2*line - 1
  f_list = list(range(leng+2)) # Pre-distribution, insert At the beginning hu will slow down, at the bottom 1 Yes, right and left 1 A blank space 
  # All initialized to 0
  for i,v in enumerate(f_list):
    f_list[v] = 0
  ZEROLIST = f_list[:] # The reserved 1 It's an array of all zeros 
  f_list[leng//2] = 1 # The initial of the first 1 line 
  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 # To calculate 1 The first in line 1 a 1 The location of the 
    end = start + 2*n # To calculate 1 Line of the last 1 a 1 The location of the 
    while start <= end:
      re_list[start] = f_list[start - 1] + f_list[start+1] # Whether or not 1 , the position of the number, are up 1 Row the sum of the left and right digits at that position 
      start = start + 1
  return 'done'

def printList(L):
  n = 0
  p_str = ''
  for value in L:
    ch = str(value)
    if value == 0:
      ch = ' '
    p_str = p_str + ch
  print(p_str)

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

Related articles: