用python的列表生成式和generator写杨辉三角

Problem Description

杨辉三角定义如下:

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

把每一行看做一个list,试写一个generator,不断输出下一行的list:
期待输出:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]

Mentality

generator用法:
例子:打印10之内(不包括10)的数字的平方值

>>> g = (x * x for x in range(10))# 不包括10,也就是从0到9,一共10个数
>>> for n in g:
...     print(n)
... 
0
1
4
9
16
25
36
49
64
81

若要将一个函数改为generator,可以通过修改print为yield实现:

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return 'done'
########################
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'

>>> f = fib(6)
>>> f
<generator object fib at 0x104feaaa0>

函数与generator的区别:函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next() 的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

思路:将函数修改为generator,每行是一个list,可以用列表生成式实现。

Code (C++)

# -*- coding: utf-8 -*-
def triangles():
    L=[1]
    while True:
        yield L
        newL = [ L[i]+L[i+1] for i in range(len(L)-1)]
        L = newL
        L.insert(0,1)
        L.append(1)

测试代码为:

n = 0
results = []
for t in triangles():
    results.append(t)
    n = n + 1
    if n == 10:
        break

for t in results:
    print(t)

if results == [
    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1],
    [1, 4, 6, 4, 1],
    [1, 5, 10, 10, 5, 1],
    [1, 6, 15, 20, 15, 6, 1],
    [1, 7, 21, 35, 35, 21, 7, 1],
    [1, 8, 28, 56, 70, 56, 28, 8, 1],
    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
    print('测试通过!')
else:
    print('测试失败!')

输出结果为:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
测试通过!
发布了19 篇原创文章 · 获赞 10 · 访问量 1201

猜你喜欢

转载自blog.csdn.net/qq_38655181/article/details/105520441