分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
YangHuiTriangle.py - by Chimomo
"""
# Triangle generator.
def generate_triangle():
li = [1]
while True:
yield li
li = [1] + [li[i] + li[i + 1] for i in range(0, len(li) - 1)] + [1]
# Get m_triangles within rank = (rank).
def get_triangles(rank):
triangles = [[1]]
i = 0
for tri in generate_triangle():
i += 1
# Continue the loop since m_triangles is already initialized with [[1]].
if i == 1:
continue
triangles.append(tri)
if i == rank:
return triangles
# Print m_triangles with well format.
def print_triangles(triangles, width):
column_width = len(triangles[:]) * width
for triangle in triangles:
triangle_line = []
for triangle_content in triangle:
triangle_line.append('{0:^{1}}'.format(str(triangle_content), width))
print('{0:^{1}}'.format(''.join(triangle_line), column_width))
m_triangles = get_triangles(6)
print_triangles(m_triangles, len(m_triangles[:-1][len(m_triangles[:-1]) // 2]) + 3)
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]
layer = 0
results = []
for t in generate_triangle():
print(t)
results.append(t)
layer = layer + 1
if layer == 10:
break
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('测试失败!')
# Output:
'''
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
开始测试
[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]
测试通过!
'''