用python输出杨辉三角

6284阅读 0评论2012-02-08 wenhaoz
分类:Python/Ruby

在网上发现高人写的代码,转一下,太经典了。
这是普通的写法:
  1. '''
  2.     Pascal's triangle:

  3.     for x in pascals_triangle(5):
  4.         print('{0:^16}'.format(x))

  5.           [1]
  6.          [1, 1]
  7.        [1, 2, 1]
  8.       [1, 3, 3, 1]
  9.     [1, 4, 6, 4, 1]
  10.     ''
  1. ## {{{ http://code.activestate.com/recipes/577542/ (r5)
  2. def pascals_triangle(n):
  3.     x=[[1]]
  4.     for i in range(n-1):
  5.         x.append([sum(i) for i in zip([0]+x[-1],x[-1]+[0])])
  6.     return x
  7. ## end of http://code.activestate.com/recipes/577542/ }}}
另一种风格:
  1. def pascals_triangle(n):
  2.     x=[[1]]
  3.     for i in range(n-1):
  4.         x.append(list(map(sum,zip([0]+x[-1],x[-1]+[0]))))
  5.     return x
最牛逼的:
  1. pascals_triangle=lambda n:[[i for i in str(11**j)] for j in range(n)]
上一篇:利用数组进行数据查找
下一篇:python判断是否为回文