Search code examples
pythoncombinationsparenthesescalculation

Try all possible parenthesis placement on a math calculation


so I have a list with number and math operators.

number = ['10', '6', '2', '6', '3', '1'] 
operators = ['+', '*', '//, -,'+']

Then I build my statement like that

calculation = num[0] + operator[0] + num [1] ...

Now I took a function I found here to generate all valid parenthesis.

def parens(left, right, string):
    if left == 0 and right == 0:
        arr.append(string)

    if left > 0:
        parens(left - 1, right + 1, string + "(")

    if right > 0:
        parens(left, right - 1, string + ")")

That now spits out an list called parentheses, that contains all combinations

One possible combination is now [(((((())))))] now I put it in the Equation like that.

 for index_paranthesis in range(0, 12, 2):    # Steps of two, to get all uneven parenthesis
    calculation += parenthesis[index_paranthesis] 

    calculation += number[i_number]
    i_number += 1

    calculation += parenthesis[index_paranthesis + 1] #to get the even indexed parenthesis

    calculation += operators[i_operator]
    i_operator += 1

So after that i get the first, combination of parenthesis like

calculation = (10(+(6(*(2(//)6)-)3)+)1)

So the problem now is that with eval(calculation). It says that that is a syntax error. I know thats the problem but my question is how to I get all functional parenthesis combination and apply them. Thanks for your time all ready and I hope you can help me.


Solution

  • You could just use the 'easier to ask for forgiveness than permission' approach and enclose your eval in a try/except.

    try:
        eval(expression)
    except SyntaxError:
        pass