Embercode
✕
Recursion and BacktrackingQuick quiz

Parentheses

6 questions. Covers Balanced parentheses in Python.

Questions 1 to 5 of 6

  1. 1. What does this program print? ``python tried = 0 def is_balanced(s): depth = 0 for c in s: depth += 1 if c == "(" else -1 if depth < 0: return False return depth == 0 def all_strings(length, current, result): global tried if len(current) == length: tried += 1 text = "".join(current) if is_balanced(text): result.append(text) return current.append("(") all_strings(length, current, result) current.pop() current.append(")") all_strings(length, current, result) current.pop() result = [] all_strings(8, [], result) print(f"tried={tried} valid={len(result)}") ``
  2. 2. What does this program print? ``python def build(n, open_count, close_count, current, result): if len(current) == 2 * n: result.append("".join(current)) return if open_count < n: current.append("(") build(n, open_count + 1, close_count, current, result) current.pop() if close_count < open_count: current.append(")") build(n, open_count, close_count + 1, current, result) current.pop() zero = [] build(0, 0, 0, [], zero) print(f"n=0 count={len(zero)} list={zero}") two = [] build(2, 0, 0, [], two) print(f"n=2 second={two[1]} first={two[0]}") ``
  3. 3. The line that checks open_count was changed, and the code below is meant to list the valid strings for n = 1. What does the last line print? ``python def build(n, open_count, close_count, current, result): if len(current) == 2 * n: result.append("".join(current)) return if open_count <= n: current.append("(") build(n, open_count + 1, close_count, current, result) current.pop() if close_count < open_count: current.append(")") build(n, open_count, close_count + 1, current, result) current.pop() result = [] build(1, 0, 0, [], result) print(result) ``
  4. 4. The is_balanced function below has its early return removed. What does the program print? ``python def is_balanced(s): depth = 0 for c in s: depth += 1 if c == "(" else -1 return depth == 0 print(is_balanced(")(")) print(is_balanced("(()())")) print(is_balanced("())(")) ``
  5. 5. For n pairs of brackets, which check belongs in the base case that saves a finished string?

5 question(s) left on this page.