编写程序打印如下图案:(五行九列) * *** ***** ******* *********
时间: 2023-12-18 08:29:27 浏览: 89
计算两个5*5矩阵的乘积
以下是Python实现的代码,可以根据用户输入的w、s、x键来放大、缩小、切换数字和星号的图案:
```python
import sys
# 初始化图案
pattern = [[' ' for j in range(9)] for i in range(5)]
pattern[0][4] = '*'
pattern[1][3:6] = ['*', '*', '*']
pattern[2][2:7] = ['*', '*', '*', '*', '*']
pattern[3][1:8] = ['*', '*', '*', '*', '*', '*', '*']
pattern[4] = ['*', '*', '*', '*', '*', '*', '*', '*', '*']
# 打印图案
def print_pattern():
for row in pattern:
print(''.join(row))
# 计算数字
def calc_num(i, j):
if i == 0:
return 1
elif i == 1:
return j - 3
else:
return sum([int(pattern[i-1][k] == '*') for k in range(j-2, j+3)])
# 将星号替换为数字
def replace_star_with_num():
for i in range(5):
for j in range(9):
if pattern[i][j] == '*':
pattern[i][j] = str(calc_num(i, j))
# 将数字替换为星号
def replace_num_with_star():
for i in range(5):
for j in range(9):
if pattern[i][j].isdigit():
pattern[i][j] = '*'
# 放大图案
def zoom_in():
new_pattern = [[' ' for j in range(18)] for i in range(10)]
for i in range(5):
for j in range(9):
new_pattern[2*i][2*j] = pattern[i][j]
new_pattern[2*i][2*j+1] = pattern[i][j]
new_pattern[2*i+1][2*j] = pattern[i][j]
new_pattern[2*i+1][2*j+1] = pattern[i][j]
return new_pattern
# 缩小图案
def zoom_out():
new_pattern = [[' ' for j in range(9)] for i in range(5)]
for i in range(0, 9, 2):
for j in range(0, 5, 2):
if pattern[j][i] == pattern[j][i+1] == pattern[j+1][i] == pattern[j+1][i+1]:
new_pattern[j//2][i//2] = pattern[j][i]
else:
return pattern
return new_pattern
# 主程序
while True:
print_pattern()
cmd = input('请输入命令(w:放大,s:缩小,x:切换数字和星号,q:退出):')
if cmd == 'w':
pattern = zoom_in()
elif cmd == 's':
pattern = zoom_out()
elif cmd == 'x':
if pattern[0][0].isdigit():
replace_num_with_star()
else:
replace_star_with_num()
elif cmd == 'q':
sys.exit()
```
阅读全文