Syngularity
Syngularity

Reputation: 824

Put parenthesis in to string python

I have an input string like this :

f(x, 3*y) * 54 = 64 / (7 * x) + f(2*x, y-6)

I want to get this output:

(x / (3*y)) * 54 = 64 / (7 * x) + ((2*x) / (y-6))

The rule: the parenthesis marked with 'f', remove the 'f' and the ',' mark have to change to /. If one of the sides contain an expresion it have to be put in to parenthesis f(2 , 2 + x) = (2 / (2 + x))

I have code that works for most test input but, in some test cases, it generates the wrong output:

line = sub(r"f\((.+?) *, *(.+?)\)", r"(\1 / \2)", (sub(r"f\((.+?[\+-/\*]+.+?) *, *(.+?)\)", r"f((\1),\2)", (sub(r"f\((.+?) *, *(.+?[\+-/\*]+.+?)\)", r"f(\1,(\2))", line)))))

This is the code I have written. As I mentioned, it works well, but for this line:

f(x, 3*y) * 54 = 64 / (7 * x) + f(2*x, y-6)

I get this result:

((x / (3*y)) * 54 = 64 / (7 * x) + (2*x) / (y-6))

One of the parentheses is in the wrong place. I have no idea what the problem is.

Upvotes: 1

Views: 23535

Answers (1)

P0W
P0W

Reputation: 47784

Your regex is too complex.

If x and (x) doesn't matter you could simply use :

regex pattern : f\((\S+?),\s+(\S+)?\) and

replace it with : \( \(\1\) / \(\2\) \)

This will give

( (x) / (3*y) ) * 54 = 64 / (7 * x) + ( (2*x) / (y-6) )

for f(x, 3*y) * 54 = 64 / (7 * x) + f(2*x, y-6)

Upvotes: 3

Related Questions