Python solution using recursive evaluation - very self-explained


  • 0
    M
    class Solution(object):
        def diffWaysToCompute(self, input):
            rt=[];
            
            if "+" not in input and "-" not in input and "*" not in input:
                return [int(input)];
            elif input.count("+")+input.count("-")+input.count("*")==1:
                return [eval(input)];
            else:
                signIndexList=[];
                signList=[];
                for i in range(len(input)):
                    if input[i]=="+" or input[i]=="-" or input[i]=="*":
                        signIndexList.append(i);
                        signList.append(input[i]);
                        
                for j in range(0,len(signIndexList)):
                    fstHf=self.diffWaysToCompute(input[0:signIndexList[j]]);
                    sndHf=self.diffWaysToCompute(input[signIndexList[j]+1:]);
                    for f in fstHf:
                        for s in sndHf:
                            rt.append(eval(str(f)+signList[j]+str(s)));
                            
                return rt;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.