矩阵程序要求用户输入

时间:2016-12-29 13:14:31

标签: python

# 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)

这里我有一个程序可以计算矩阵,但我想知道如何在运行程序时询问用户输入而不是事先输入数字

1 个答案:

答案 0 :(得分: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)