程序我编写了一个程序,以便main调用以下函数:
getMatrix - 创建并返回3 x 3矩阵
printMatrix - 逐行打印矩阵
sumRow - 返回矩阵单行元素的总和(传递矩阵和行索引)
我面临的问题是它要求输入两次,而不是一次。
def getMatrix():
matrix = []
numberOfRows = eval(input("Enter the number of rows: "))
numberOfColumns = eval(input("Enter number of columns: "))
for row in range(numberOfRows):
matrix.append([])
for column in range(numberOfColumns):
value = eval(input("Enter an element and press enter: "))
matrix[row].append(value)
return matrix
# Print 2 dimensional list
def printMatrix(matrix):
matrix = getMatrix()
for row in range(len(matrix)):
for column in range(len(matrix[row])):
print(matrix[row][column], end = " ")
print()
# Add each element in row to total
def sumRow(matrix):
for row in range(len(matrix[0])):
total = 0
for column in range(len(matrix)):
total += matrix[row][column]
print("Sum for matrix", row, "is", total)
def main():
matrix = getMatrix()
printMatrix(matrix)
total = sumRow(matrix)
main()
答案 0 :(得分:0)
在main
:
matrix = getMatrix()
printMatrix(matrix)
在printMatrix
:
matrix = getMatrix()
顺便说一下,它会立即掩盖你传入的matrix
参数。
在getMatrix
:
matrix = []
numberOfRows = eval(input("Enter the number of rows: "))
numberOfColumns = eval(input("Enter number of columns: "))
顺便说一下,您应该使用int()
,而不是eval()
。
因此有两次调用getMatrix()
,这意味着有两个输入请求。从matrix = getMatrix()
移除printMatrix
。无论如何,这不是该功能应该做的事情。
答案 1 :(得分:0)
使用此代码,您可以打印任何 m x n 矩阵:
row = int(input("Enter number of rows you want: "))
col = int(input("Enter number of columns you want: "))
mat = []
for m in range(row):
a = []
for n in range(col):
a.append(0)
mat.append(a)
for i in range(len(mat)):
for j in range(len(mat[0])):
mat[i][j] = int(input("Input element: "))
print("Your Matrix is: ", mat)