Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Dakshesh Jain
This is the same solution but with Return Early.

Dakshesh Jain

Mar 19, 2024

This is the same solution but with Return Early, many programmers myself included find this more readable.

class Solution:   def diffWaysToEvaluateExpression(self, input):     result = []     # return early instead of using else condition     if "+" not in input and "*" not in input and "-" not in input:       result.append(int(input))       return result # continue program if condition is not met     for i in range(len(input)):       char = input[i]       if char.isdigit(): # this also avoids nesting         continue       left_part = self.diffWaysToEvaluateExpression(input[0:i])       right_part = self.diffWaysToEvaluateExpression(input[i+1:])       for part_1 in left_part:         for part_2 in right_part:           if char == "+":             result.append(int(part_1 + part_2))           elif char == "*":             result.append(int(part_1 * part_2))           elif char == "-":             result.append(int(part_1 - part_2))     return result

1

0

Comments
Comments
S
Silencer312 2 years ago

I mean its the same thing

On this page