Discuss / Python / 作业

作业

Topic source

整理了一下,自己能力有限,非原创

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#第一种方法:triangles函数定义的时候无输入参量指定循环次数,即一直循环,需要在调用函数(利用for函数)中为添置一个中断条件
def triangles():
    N = [1]
    while True:
        yield N
        N.append(0)
        N = [N[i-1] + N[i] for i in range(len(N))] 
n = 0
for t in triangles():
    print(t)
    n=n+1
    if n == 10:
        break
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#第二种方法:triangles函数定义的时候有输入参量指定循环次数
def triangles(max):
    N = [1]
    n=0
    while n<max:
        yield N
        N.append(0)
        N = [N[i-1] + N[i] for i in range(len(N))] 
        n=n+1

for t in triangles(10):
    print(t)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#方法三:利用zip函数
def triangles():
    a = [1]
    while True:
        yield a
        a = [sum(i) for i in zip([0] + a, a + [0])]

n = 0
for t in triangles():
    print(t)
    n=n+1
    if n == 10:
        break

#这里用到了zip函数,zip函数基本运作方式:
#>>>x = [1, 2, 3]
#>>>y = [4, 5, 6]
#>>>z = [7, 8, 9]
#>>>zip(x, y, z)
#[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
#>>>x = [1, 2, 3]
#>>>y = [4, 5, 6, 7]
#>>>zip(x, y)
#[(1, 4), (2, 5), (3, 6)]

参考:http://www.cnblogs.com/frydsh/archive/2012/07/10/2585370.html

August_Rm

#3 Created at ... [Delete] [Delete and Lock User]

方法3:利用zip函数,在调用的时候会提示: TypeError: 'int' object is not callable 说sum()只能作用于对int对象。但我在交互环境下测试却是OK的:

a = (1,2) b = (3,4) c = [sum(i) for i in zip(a, b)] print(c) [4, 6]

以上是什么情况原因啊?如何解决呢?


  • 1

Reply