Search code examples
pythoninputreadlines

Inputlines must be converted to tuples


I have an input file that looks as follows:

4 * 2 ^ 3 + 4 ^ 1 2 * 1 ^ 2 + 2 ^ 3

and there could be more lines. What I need to do is to extract the value that is before the * sign, so for the first line that is the 4. Then I need to make a tuple g = [(2,3),(4,1)], so the tuple-pairs are separated by the + and then the pair itself by the ^.

my_input = open('input.txt').readlines()
lines = [str(line) for line in 
open('input.txt','r').read().split('\n')]
per_line = str(lines[0]).split('*')
x = int(per_line[0])
terms = str(per_line[1].split('+'))

Now if i print terms I get ['2 ^ 3 ', ' 4 ^ 1'], and if I print x I get 4, so that seems to work. But now I need to get those values in the described tuple-form. If I split again on '^' I don't get the result needed, but instead ["['2 ", " 3 ', ' 4 ", " 1']"], which isn't workable. I tried it with factors = str(terms.split('^')).

Also I need to make this an iteration so it works for all the lines, but I can do that later. I first want to make sure it works for just the first line.

Any suggestions?


Solution

  • Here is a better way to do it:

    import re
    
    x = []
    g = []
    with open('input.txt') as infile:
        for line in infile:
            nums = re.split(r'[\*\^\+]', line)
            x.append(int(nums[0]))
            g.append((int(nums[1]), int(nums[2])))
    
    print(x) # [4, 2]
    print(g) # [(2, 3), (1, 2)]