Operands and Operators are arrays containing a sequence of numbers and a sequence of
mathematical operations such as addition, multiplication. Expressions are formed by using
all operators and required amount of numbers, in their original order. They are evaluated
by bracketing from the right end.
Example expression: (3*(5+9)) which evaluates to 42. Invalid
expressions: (3+(5×9)), ((3×5)+9), (1x(3+5)) .
Is there an efficient algorithm for this problem? If yes then what is it?
Initially I tried to find some subproblems with which I could get a reccurence relation, and then maybe find some overlaps to get a D.P. algorithm. But now I think there is no other way than doing a combination and applying operations in order. Is there a better way?
Brute force code in python:
import itertools
def expression(Indices,Operand,Operator):
op = len(Operator)-1
if Operator[op] == '+':
expr = Operand[Indices[op]]+Operand[Indices[op+1]]
elif Operator[op] == '*':
expr = Operand[Indices[op]]*Operand[Indices[op+1]]
for op in range(len(Operator)-2,-1,-1):
if Operator[op] == '+':
expr = expr+Operand[ndices[op]]
elif Operator[op] == '*':
expr = expr*Operand[Indices[op]]
return expr
def find_max_exp(Operand,Operator):
X=len(Operand)
Y=len(Operator)
if Y>X+1 or X<2:
print("Not enough Operands")
N = [x for x in range(X)]
maximum = 0
for comb in itertools.combinations(N, Y+1):
indices = list(comb)
candidate = expression(indices,Operand,Operator)
if maximum<candidate:
maximum = candidate
max_ind = indices
print(maximum)
print(max_ind)
Operands = [1,3,2,1,4]
Operators = [ '*' , '+']
find_max_exp(Operands,Operators)
18
[1, 2, 4]