← Back to challenges

Evaluate the Group of Parentheses

PythonHardalgorithmslogicregexstrings

Instructions

The function is given a balanced parentheses string. Each open "(" has corresponding closed ")". Compute the total score based on the following rules:

  • Substring s = "()" has score 1,
  • Substring "s1s2" has total score as score of "s1" + score of "s2",
  • Substring "(s)" has total score as 2 * score of "s".

Calculate the total score of the given expression and return it as integer.

Examples

eval_parentheses("()") ➞ 1
# 1

eval_parentheses("(())") ➞ 2
# 2 * 1

eval_parentheses("()()") ➞ 2
# 1 + 1

eval_parentheses("((())())") ➞ 6
# 2 * (2 * 1 + 1)

eval_parentheses("(()(()))") ➞ 6
# 2 * (1 + 2 * 1)

eval_parentheses("()(())") ➞ 3
# 1 + 2 * 1

eval_parentheses("()((()))") ➞ 5
# 1 + 2 * 2 * 1

Notes

N/A

python3
Loading editor…
to run
Walks through the solution with reasoning and edge cases.