2016-12-29 103 views
0
# 3x3 
X = [[0,0,0], 
    [0 ,5,6], 
    [7 ,0,0]] 
# 3x4 
Y = [[0,0,0,0], 
    [0,0,0,0], 
    [0,0,0,0]] 
# 3x4 
result = [[0,0,0,0], 
     [0,0,0,0], 
     [0,0,0,0]] 

# iterate through rows of X 
for i in range(len(X)): 
    # iterate through columns of Y 
    for j in range(len(Y[0])): 
     # iterate through rows of Y 
     for k in range(len(Y)): 
      result[i][j] += X[i][k] * Y[k][j]   
#This code multiplies matrices X and Y and puts the resulting product into matrix result 
#It then prints the matrix result row by row, so it looks like a matrix on the screen 
for r in result: 
    print(r) 

在這裏,我有一個計劃,將制定出一個矩陣,但我不知道如何運行程序時,而不是事先輸入的數字矩陣程序要求用戶輸入

+3

什麼「用戶輸入蟒蛇」在搜索引擎回報? –

+1

http://stackoverflow.com/questions/32466311/taking-nn-matrix-input-by-user-in-python –

+0

一種自然的方法是讓用戶輸入字符串,如'[[1,2],[ 3,4]]'然後解析這些字符串(這很簡單)。 –

回答

0

詢問用戶輸入一種特別簡單的方法來從所述用戶獲得的兩個矩陣是從模塊ast使用函數literal_eval

import ast 
X = ast.literal_eval(input("Enter the first matrix as a list of lists: ")) 
Y = ast.literal_eval(input("Enter the second matrix: ")) 
#code to compute X*Y -- note that you can't hard-wire the size of result 

這種方法的優點在於,如果用戶在提示進入[[1,2],[3,4]](其產生字符串'[[1,2],[3,4]]')然後literal_eval將此字符串轉換爲列表[[1,2],[3,4]]

要使此方法健壯,您應該使用錯誤陷印來優雅地處理用戶例如錯誤地輸入[[1,2][3,4]]

至於不硬佈線的result大小:由於該產品是由行填充行,我建議通過初始化result的,因爲他們計算這些附加行空單重構你的代碼。作爲一個模板是這樣的:

result = [] 
for i in range(len(X)): 
    row = [0]*len(Y[0]) 
    for j in range(len(Y[0])): 
     # code to compute the jth element of row i 
    result.append(row)