想了半天,献丑了
Topic source个人认为您的代码最简洁, 稍微修改了一下:
def triangles():
L = [1]
while True:
yield L
L = [1] + [L[i] + L[i + 1] for i in range(len(L) - 1)] + [1]
我是这么写的,不知道为什么只能计算到[1,1],后面会报错“list object is not callable”,有哪位大神能解答一下吗
def tri(n):
L = [1]
a=1
while a<n:
yield L
L = [1] + [L[s] + L[s+1] for s in range(len(L) - 1)] + [1]
a=a+1
return 'done'
参考楼上的代码后,我的代码是这样。
def triangles():
n = 1
L = [1]
yield L
n = 2
L = [1,1]
yield L
n = 3
while True:
L = [1] + \
[L[i] + L[i+1] for i in range(n-2)] + \
[1]
yield L
n = n+1
# 杨辉三角输出
def yang(max):
yield[1]
L = [1,1]
while max >= 2:
yield L
max = max - 1
L = [1]+[L[i] + L[i+1] for i in range(len(L)-1)]+[1]
for i in yang(10):
print(i)
def triangles():
L = []
while True:
L = [ L[i]+ (0 if i == 0 else L[i-1]) for i in range(0, len(L))]+[1]
yield L[:]
我看你评论底下的代码,好像是生成器里面的列表不用担心out of range的问题???
比如生成第二行的时候,range(len(l)-1) 为空,空列表取值会报out of range的错误啊,求解释
The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty
这代码牛!!
@[:
def triangles():
L = [1]
while True:
yield L
L = [1] + [L[i] + L[i + 1] for i in range(len(L) - 1)] + [1]
- 1
hjgw
def triangles():
yield [1]
l = [1, 1]
yield l
while True:
l = [1] + [l[i] + l[i-1] for i in range(1,len(l))] + [1]
yield l