使用python生成杨辉三角形的示例代码

yipeiwu_com5年前Python基础

杨辉三角杨辉 定义如下:

     1
    / \
    1  1
   / \ / \
   1  2  1
  / \ / \ / \
  1  3  3  1
 / \ / \ / \ / \
 1  4  6  4  1
 / \ / \ / \ / \ / \
1  5  10 10 5  1

把每一行看做一个list,试写一个generator,不断输出下一行的list:

def triangles():
  L = [1]
  while True:
    yield L
    
    M=L[:]#复制一个list,这样才不会影响到原有的list。不然results里的每个列表的末尾会为0.
    M.append(0)
    L = [M[i-1]+M[i] for i in range(len(M))] 
    
n =0
results = []
for t in triangles():
  
  print(t)
  results.append(t)
  print(results)
  n = n +1
  if n == 10:
    break

ps:如何实现心

def printlove(start,length,midnumber=0,flag=31):
  for i in range(31):
    if i<start or i>start+length-1 and i<15-(midnumber-1)/2 or i>15+(midnumber-1)/2 and i<31-start-length or i> 30-start or i==flag:
      print " ",
    else:
      print "*",
  print ""
for i in range(16):
  if i ==0:
      printlove(4,3)
  elif i==1:
      printlove(1,9)
  elif i>=2 and i<=5:
      printlove(0,i+10)
  elif i==6:
      printlove(1,7,7,15)
  elif i>=7 and i<=8:
      printlove(i-5,6,5-(i-7)*2)
  elif i==9:
      printlove(5,6,1)
  elif i==10:
      printlove(8,6,1)
  elif i==15:
      printlove(15,1,1)
  else:
      printlove(i-1,16-i,1)

实现的效果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在ironpython中利用装饰器执行SQL操作的例子

比较喜欢python的装饰器, 试了下一种用法,通过装饰器来传递sql,并执行返回结果 这个应用应该比较少 为了方便起见,直接使用了ironpython, 连接的mssql server...

通过mod_python配置运行在Apache上的Django框架

为了配置基于 mod_python 的 Django,首先要安装有可用的 mod_python 模块的 Apache。 这通常意味着应该有一个 LoadModule 指令在 Apache...

python分割一个文本为多个文本的方法

本文实例为大家分享了python分割一个文本为多个文本,供大家参考,具体内容如下 # load file # for each row ## if match ## output...

如何运行.ipynb文件的图文讲解

如何运行.ipynb文件的图文讲解

首先cmd下面输入: pip install jupyter notebook,安装慢的改下pip的源为国内的源 然后cmd中输入: jupyter notebook就会弹出一个页面 先...

Python MD5文件生成码

import md5 import sys def sumfile(fobj): m = md5.new() while True: d = fobj.read(8096) if not...