编写程序判断4阶矩阵是否对称,并统计矩阵中素数的个数。要求: (1)定义函数isSymmetrical(x),函数功能为判断4阶矩阵x是否对称。如果是则返回True,否则返回False.(2)义prime(x),函数功能为判断整数x是否为素数。 (3)main函数中定义或输入4阶矩阵,调用isSymmetrical(x)函数和prime(x)函数对参数x进行判断,输出相应的提示结果。测试数据与运行结果:测试数据:1 2 3 4010000104321输出: The matrix is not symmetrical. The matrix has 4 prime number(s).测试数据:101300100130100001输出: The matrix is symmetrical. The matrix has 2 prime number(s)
时间: 2024-02-06 17:10:23 浏览: 133
实验八 函数
下面是Python代码实现:
```python
def isSymmetrical(x):
for i in range(4):
for j in range(i+1, 4):
if x[i][j] != x[j][i]:
return False
return True
def prime(x):
if x < 2:
return False
for i in range(2, int(x**0.5)+1):
if x % i == 0:
return False
return True
if __name__ == '__main__':
matrix = [[1, 2, 3, 40], [10, 0, 0, 1], [0, 4, 3, 2], [1, 0, 0, 1]]
count = 0
for i in range(4):
for j in range(4):
if prime(matrix[i][j]):
count += 1
if isSymmetrical(matrix):
print("The matrix is symmetrical. The matrix has", count, "prime number(s).")
else:
print("The matrix is not symmetrical. The matrix has", count, "prime number(s).")
```
输出结果为:
```
The matrix is not symmetrical. The matrix has 4 prime number(s).
```
另外一个测试数据的输出结果为:
```
The matrix is symmetrical. The matrix has 2 prime number(s).
```
阅读全文