Question

I would like to ask your help. I have started learning python, and there are a task that I can not figure out how to complete. So here it is.

We have a input.txt file containing the next 4 rows:

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

x + f(21*y, x - 32/y) + 4 = f(21 ,y)

86 - f(7 + x*10, y+ 232) = f(12*x-4, 2*y-61)*32 + f(2, x)

65 - 3* y = f(2*y/33 , x + 5)

The task is to change the "f" function and its 2 parameters into dividing. There can be any number of spaces between the two parameters. For example f(2, 5) is the same as f(2 , 5) and should be (2 / 5) with exactly one space before and after the divide mark after the running of the code. Also, if one of the parameters are a multiplification or a divide, the parameter must go into bracket. For example: f(3, 5*7) should become (3 / (5*7)). And there could be any number of function in one row. So the output should look like this:

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

x + ((21*y) / (x - 32/y)) + 4 = (21 / y)

86 - ((7 + x*10) / (y+ 232)) = ((12*x-4) / (2*y-61))*32 + (2 / x)

65 - 3* y = ((2*y/33) / (x + 5))

I would be very happy if anyone could help me.

Thank you in advance, David

Was it helpful?

Solution

Using re:

In [84]: ss=r'f(x, 3*y) * 54 = 64 / (7 * x) + f(2*x, y-6)'

In [85]: re.sub(r'(f\()(.*?),(.*?)(\))', lambda m: '((%s) / (%s))'%(m.group(2), m.group(3)), ss)
Out[85]: '((x) / ( 3*y)) * 54 = 64 / (7 * x) + ((2*x) / ( y-6))'

Explanation:

  1. re.sub(pattern, repl, string, count=0, flags=0) returns the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl.

  2. The () are used to catch the groups;

  3. *? is a non-greedy qualifier, which matches as little text as possible.

OTHER TIPS

Here's some places to start:

  • You can check if one string is in another string using string1 in string2 (e.g., 'bcd' in 'abcdefg' -> True)
  • You can identify the insides of f() calls by finding the locations of 'f(' in a string and then adding 1 to an index (that starts at 1) when you find a '(' and removing 1 when you find ')'. When you hit 0 you're done.
  • You can break a string into a list by a matching string by string1.split(string2) (e.g., 'a,b'.split(',') -> ['a', 'b']
  • You can format a string easily using the .format method (e.g., '({0} % {1})'.format(string1, string2))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top