88. Balanced brackets, all of them
A string of brackets is balanced when every ( is closed by a later ) and no ) comes before its (: (())()
is balanced, ())( isn't.
Write a function balanced(n) that takes a whole number n and returns every balanced string made of n pairs of
brackets, that is n of ( and n of ):
- Each string appears once.
- The list is sorted in dictionary order, where
(comes before). (That is Python's own order for these two characters, sosorted()gives it.) - With
n = 0the only balanced string is the empty one:[""].
Writing out every string of ( and ) and keeping the balanced ones works, but most of them are thrown away. It is
better never to build a string that can't end up balanced.
Example 1
n = 1["()"]Example 2
n = 2["(())", "()()"]Example 3
n = 0[""]Constraints
nis a whole number from 0 to 6.
Submit also runs 3 more tests you can't see.
Practises Recursion (lesson 20).
- Build the strings one bracket at a time with a helper that knows how many
(and)it has used so far. - An
(can be added while fewer thannhave been used. A)can be added only while it has an open(to close: fewer)than(so far. - A string is finished at length
2 * n. If the helper tries(before), the strings come out already in dictionary order.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def balanced(n):
"""List every balanced string of n bracket pairs.
n: int, 0 or more
Returns: list of str, each balanced string once, in
dictionary order with "(" before ")"
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.