diff options
author | Jack Sangdahl <[email protected]> | 2025-10-01 09:45:51 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-10-01 09:45:51 -0600 |
commit | 01585d45e77abeb96336aac00896b11ad0298956 (patch) | |
tree | 13040ddfcb5ebc6cbc003af5c502b36ccc2610bf /minimize_result_add_parentheses.py | |
parent | 9885ede0c5c6394f0196b2e7d459105d77749c07 (diff) | |
download | leetcode-01585d45e77abeb96336aac00896b11ad0298956.tar.gz leetcode-01585d45e77abeb96336aac00896b11ad0298956.zip |
2232. minimise result by addding parenthesese to expression
Diffstat (limited to 'minimize_result_add_parentheses.py')
-rw-r--r-- | minimize_result_add_parentheses.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/minimize_result_add_parentheses.py b/minimize_result_add_parentheses.py new file mode 100644 index 0000000..b59eca3 --- /dev/null +++ b/minimize_result_add_parentheses.py @@ -0,0 +1,33 @@ +# 2232. Minimize Result by Adding Parentheses to Expression + +""" +you are given a 0-indexed string 'expression' of the form 'num1+num2' where +'num1' and 'num2' represent integers. add a pair of parentheses to +'expression' such that after the addition of parentheses, 'expression' is a +valid mathematical expression and evaluates to the smallest possible value. +the left parenthesis must be added to the left of '+', and the right +parenthesis must be added to the right of '+'. return 'expression' after +adding a pair of parentheses such that 'expression' evaluates to the smallest +possible value. if multiple answers that yield the same result, return any of +them. +""" + + +class Solution(object): + def minimizeResult(self, expression): + """ + :type expression: str + :rtype: str + """ + left, right = expression.split("+") + value = lambda s: eval(s.replace("(", "*(").replace(")", ")*").strip("*")) + l = [left[0:i] + "(" + left[i:] for i in range(len(left))] + r = [right[0:i] + ")" + right[i:] for i in range(1, len(right) + 1)] + return min([i + "+" + j for i in l for j in r], key=value) + + +if __name__ == "__main__": + obj = Solution() + print(obj.minimizeResult(expression="247+38")) + print(obj.minimizeResult(expression="12+34")) + print(obj.minimizeResult(expression="999+999")) |