Saturday 15 May 2010

isa swizzling - I'm having trouble adding two matrices in python -


I want to add two motherhood to dragon 3, but the problem is that when i input Adding the program

This is my code

  def addmatrix (a, b): d = [] n = 0 while n & lt; Lane (A): C = [] K = 0 while K & lt; Lane (a [0]): c.append (a [n] [k] + b [n] [k]) k + = 1 n + 1 d.append (c) return ddef main (): a = Input (insert a matrix: ") B = input (" Enter other matrix: ") Print (Adometrics (A, B)) Main ()   

If input is

Enter a matrix: [[5,6], [1,2], [2,4]]

Enter another matrix: [[2,3], [-6,0], [-2, 4]]

comes in the form of output [['[[['], ['[[[ '' ['52'], [','], ['63'], [']]'], [','], ['], [' [['], [' 1- '', '[', 6 '], [' 2, '], ['] 0 '], [',] '], [', '], [' ['], [' 2 '], [',' '], [' 42 '], ['], '], ['] ']]]

But if I input from the program and make it so that

  def (main): a = [[5,6], [1,2], [2, 4]] B = [[2,3], [-6,0], [-2, 4]] print (admatrix (A, B)) main ()   

output Then comes as the [[7, 9], [-5, 2], [0, 8]] which is correct.

Is there any way that I Can my program work so that when a person joins two matrix together? I am new in Python so any help would be appreciated :)

You have to convert the user Now input into a python object, this is a string.

You can use eval (if not should be used, if you do not know what your users will input I I can type in __ import __ ('OS') system ('rm /some/file.txt') and Python will delete a file):

  a =   

or you can use ast.literal_eval , which is secure: Import from literal_eval ... a = Literal_eval (input ("Enter a matrix:"))

No comments:

Post a Comment