Gangmax Blog

Python generator

From here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def triangles(n):
result = [1, 1]
for i in range(1, n + 1):
if i == 1:
yield [1]
elif i == 2:
yield [1, 1]
else:
next_result = [result[0]]
for j in range(1, len(result)):
next_result.append(result[j-1] + result[j])
next_result.append(result[-1])
result = next_result
yield result

def print_triangels(n):
for i in triangles(n):
print(i)

print_triangels(10)

Comments