编写函数,打印杨辉三角
时间: 2024-02-17 19:03:14 浏览: 23
好的,以下是 Python 代码示例,实现打印杨辉三角的函数:
```python
def print_yanghui_triangle(n):
if n <= 0:
return
triangle = [[1]]
for i in range(1, n):
row = [1]
for j in range(1, i):
row.append(triangle[i-1][j-1] + triangle[i-1][j])
row.append(1)
triangle.append(row)
max_width = len(str(triangle[-1][-1]))
for row in triangle:
for num in row:
print(f"{num:{max_width}}", end=" ")
print()
```
这个函数的参数 `n` 是要打印的杨辉三角的行数,函数使用二维列表存储杨辉三角的数值,然后按照格式化字符串的方式打印每个数。
你可以像这样通过调用函数来打印一个杨辉三角:
```python
print_yanghui_triangle(6)
```
示例输出:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
希望这个示例能够帮到你!
相关问题
头歌实训python编写函数打印杨辉三角前n行
以下是Python编写的函数,用于打印杨辉三角前n行:
```python
def print_yanghui_triangle(n):
triangle = []
for i in range(n):
row = [1] * (i+1)
for j in range(1, i):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
for row in triangle:
print(" ".join(str(num) for num in row).center(n*3))
```
使用方法:
```python
print_yanghui_triangle(5)
```
输出结果:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
js 递归函数打印杨辉三角
好的,以下是用 JavaScript 编写的递归函数打印杨辉三角的代码:
```javascript
function yanghui(n) {
if (n === 1) {
return [1];
} else {
const last = yanghui(n - 1);
const current = [1];
for (let i = 1; i < n - 1; i++) {
current[i] = last[i - 1] + last[i];
}
current.push(1);
console.log(current.join(' '));
return current;
}
}
function printYanghui(n) {
for (let i = 1; i <= n; i++) {
yanghui(i);
}
}
printYanghui(5);
```
输出结果如下:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
注:以上代码中的 `printYanghui` 函数调用了 `yanghui` 函数,后者返回一个数组并打印出该数组中的元素。`yanghui` 函数通过递归实现了杨辉三角的生成。