当前位置: 动力学知识库 > 问答 > 编程问答 >

python - matrices program asking for user input

问题描述:

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

here i have a program that will work out a matrix but i was wondering on how to ask the user for the input when running the program instead of inputting the numbers beforehand

网友答案:

A particularly easy way to get two matrices from the user is to use the function literal_eval from the module ast:

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

The beauty of this approach is that if the user enters [[1,2],[3,4]] at the prompt (which yields the string '[[1,2],[3,4]]') then literal_eval converts this string to the list [[1,2],[3,4]].

To make this approach robust you should use error-trapping to gracefully handle situations where the user e.g. enters [[1,2][3,4]] by mistake.

As far as not hard-wiring in the size of result: Since the product is filled in row by row, I recommend refactoring your code by initializing result as an empty list to which rows are appended as they are calculated. As a template something like:

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) 
分享给朋友:
您可能感兴趣的文章:
随机阅读: