1

I want to add two matrcies in python 3 but the problem comes when I add input to the program

Here is my code

def addmatrix(a,b):
    d=[]
    n=0
    while n < len (a):
        c = []
        k = 0
        while k < len (a[0]) : 
            c.append(a[n][k]+b[n][k])
            k += 1 
        n += 1
        d.append (c)
    return d

def main():
    a = input("Enter a Matrix: ")
    b = input("Enter another Matrix: ")
    print (addmatrix(a,b))
main()

If the input is

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

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

The output comes out as [['[['], ['[['], ['52'], [',,'], ['63'], [']]'], [',,'], [' '], ['[['], ['1-'], [',6'], ['2,'], [']0'], [',]'], [' ,'], ['[ '], ['2['], [',-'], ['42'], ['],'], ['] ']]

But if I take out the 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 (addmatrix(a,b))
main()

The output then comes out as [[7, 9], [-5, 2], [0, 8]] which is correct.

Is there a way I can make my program work so that when a person inputs two matrices they add together? I'm new at python so any help will be appreciated :)

Jett
  • 2,421
  • 5
  • 16
  • 14

2 Answers2

3

You will have to convert the user input into a Python object. Right now, it's a string.

You can use eval (which should not be used if you don't know what your users will input. I can type in __import__('os').system('rm /some/file.txt') and Python will delete a file):

a = eval(input("Enter a Matrix: "))

Or you can use ast.literal_eval, which is safe:

from ast import literal_eval

...

a = literal_eval(input("Enter a Matrix: "))
Blender
  • 289,723
  • 53
  • 439
  • 496
0

Try this:

import ast

def addmatrix(a,b):
    return [map(sum, zip(*x)) for x in zip(a,b)]

def main():
    a = ast.literal_eval(raw_input("Enter a Matrix: "))
    b = ast.literal_eval(raw_input("Enter another Matrix: "))
    print addmatrix(a,b)

main()
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52