0
我寫了一個程序,使得主調用以下功能的程序:的Python 3-矩陣輸入
getMatrix - 創建並返回一個3×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()