First Last
First Last

Reputation: 200

Function for balancing parentheses

I am trying to implement a function for balancing parentheses of a given math equation as a string. It should be changing the string, not just checking if it is balanced.

Because the math equation can contain trigonometric functions, I want to add radians() after such functions, because in Python, trigonometric functions take input as radians, while I want degrees.

So tan(65) becomes tan(radians(65)).
cos(65) + sin(35) becomes cos(radians(65)) + sin(radians(35))
cos((30 - 10) * 2) becomes cos(radians((30 - 10) * 2))

So far, what I've done is using replace() to replace cos( with cos(radians(, sin( with sin(radians( and the same thing goes for all the rest trigonometric functions. But the problem is, the string (which is a math equation) becomes parentheses-unbalanced.

How do I write a function to solve this problem?

Upvotes: 2

Views: 274

Answers (2)

jp48
jp48

Reputation: 1366

You can replace cos with cosdeg and define:

def cosdeg(x):
   return cos(radians(x))

Or (lambda version):

cosdeg = lambda x : cos(radians(x))

And in a similar way with the other trig functions.

Upvotes: 2

Rory Daulton
Rory Daulton

Reputation: 22564

Here is an outline of an algorithm to both insert radians( at the proper place and keep the parentheses balanced. This will work if the parentheses are indeed balanced beforehand and if there are no unbalanced parentheses in string literals such as len("abc(d"). It does not seem terribly pythonic, however.

Do not just use replace(). Instead, use find() to find a usage of cos( or other trig function. Set a counter to zero. Then scan the string from immediately after that opening parenthesis [the ( in cos(] to the right. When you encounter an opening parenthesis, increment the counter by one; when you encounter a closing parenthesis, decrement the counter by one. When your counter reaches -1 you have found the close parenthesis for your trig function. Insert a new close parenthesis at that location, then insert your radians( just after the trig function.

Continue this until you have treated all the trig functions in your string.

Upvotes: 1

Related Questions