2016-04-27 140 views
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() 

回答

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(),這意味着兩個請求輸入。從printMatrix刪除matrix = getMatrix()。無論如何,這不是該功能所應該做的。