【发布时间】:2021-12-01 14:38:25
【问题描述】:
在函数输入中,当第一次参数为 (n, a) 时,它工作正常 a 作为用 0 初始化的空列表。但在第二次时,当 b 矩阵作为参数 (n,b) 时,所以在之前由函数返回的 li 列表将作为矩阵 b 而不是由 0 初始化的空矩阵 b。有人请帮我在我的代码中查找错误。
#funtion for taking input in matrix
def entery(n, li):
print(li)
print('enter the element of matrix: ')
for a in range(n):
for b in range(n):
no = int(input())
li[a][b]= no
return li #returning the updated matrix
n = int(input('dimensions of square matrix:'))
a = []
c = []
result = []
#creating matrix
for i in range(n):
b =[]
for j in range(n):
b.append(0)
a.append(b)
c.append(b)
result.append(b)
print("a matrix",a)
print("c matrix",c)
fm = []
sm = []
#calling function
fm = entery(n,a)
sm = entery(n,c)
print(fm)
print(sm)
#addition of matrix
for x in range(n):
for y in range(n):
result[x][y] = fm[x][y] + sm[x][y]
print(result)
输出如下图-
output:
dimensions of square matrix:2
a matrix [[0, 0], [0, 0]]
c matrix [[0, 0], [0, 0]]
[[0, 0], [0, 0]] #when called first time
enter the element of matrix:
11
22
33
44
[[11, 22], [33, 44]] # but in second time...
enter the element of matrix:
12
23
34
45
[[12, 23], [34, 45]]
[[12, 23], [34, 45]]
[[24, 46], [68, 90]]
【问题讨论】:
标签: python matrix memory-management function-call