杨辉三角是一个经典的数学图形,不仅在数学领域有重要意义,在编程中也是锻炼逻辑思维的好素材!今天就用Python来玩转它,带你体验三种不同的实现方式吧~✨
首先登场的是迭代法!通过嵌套列表和循环结构,逐步构建每一行的数据。这种方法简单直观,就像搭积木一样,一层层搭建出完整的三角形。👇
```python
def yanghui_iter(n):
result = [[1]]
for i in range(1, n):
row = [1]
for j in range(1, i):
row.append(result[i-1][j-1] + result[i-1][j])
row.append(1)
result.append(row)
return result
```
接着是递归法,利用函数调用来生成每一层数据,代码虽然简洁,但需要理解递归的精髓哦~🧐
```python
def yanghui_rec(row, depth=1):
if depth > row:
return []
else:
new_row = [1]
last_row = yanghui_rec(row, depth+1)
if last_row:
for i in range(len(last_row)-1):
new_row.append(last_row[i] + last_row[i+1])
new_row += [1]
return new_row
```
最后是组合数学法,基于公式直接计算每一项值,效率更高!⚡️
```python
from math import comb
def yanghui_math(n):
return [[comb(i, j) for j in range(i+1)] for i in range(n)]
```
三种方法各有千秋,快来试试看吧!💡