1

I am to manually merge two given matrices contained in a text file without importing any kind of module. It looks like:

[[1,2][3,4]],[[5,6,7],[8,9,10]]

I have this code:

def combine(filename): 
    with open(filename, 'r') as myfile:
        data=myfile.read().split()
        a=data[0].split()
        b=data[1].split()
    a=eval(a[0])
    b=eval(b[0])
    row_a=len(a)
    row_b=len(b)
    col_a=len(a[0])
    col_b=len(b[0])
    concatenated=[]
    if row_a==row_b: #build horizontally 
        for i in range (row_a):
            concatenated.append(a[i])
            for i in range (row_b):
                concatenated.append(b[i])
        return concatenated
    if col_a==col_b: #build vertically
        for i in range (col_a):
            concatenated.append(a[i])
            for i in range (col_b):
                concatenated.append(b[i])
        return concatenated
    else:
        print ("Error")

But it returns:

[[1, 2], [5, 6, 7], [8, 9, 10], [3, 4], [5, 6, 7], [8, 9, 10]]

Instead of:

[[1,2,5,6,7],[3,4,8,9,10]]

Any ideas on how I can make this work? Thank you in advance!

1 Answer 1

2

You can use ast.literal_eval:

import ast
final_results = [a+b for a, b in zip(*ast.literal_eval(open('filename.txt')))]

Output:

[[1, 2, 5, 6, 7], [3, 4, 8, 9, 10]]

Edit: without any imports, you can use eval. Note however that eval is quite insecure and thus must only run on strings from a trusted source:

final_results = [a+b for a, b in zip(*eval(open('filename.txt').read()))]
Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way to do this without using import? :) Thank you!
Thank you, if I were to just edit my existing code, is it not possible to just put concatenated=[a+b] under the if statements?
@FatCat please post the contents of concatenated just under the if statements.
Would you know why I get a TypeError: eval() arg 1 must be a string, bytes or code object when I try doing this?
@FatCat please see my recent edit. It should work now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.