The question is in the commented part.
The problem is My code always return the result that is 2*n , not n. For example if I want get the result of n = 6. I actually Have to call balanced(3). How to solve this problem.
def balanced(n):
'''
Given a positive number n, yield all strings of length n, in any
order, that only contain balanced brackets. For example:
>>> sorted(list(balanced(6)))
['((()))', '(()())', '(())()', '()(())', '()()()']
'''
if n == 0:
yield ''
pass
else:
for i in range(n):
for x in balanced(i):
for y in balanced(n-i-1):
yield '(' + x +')' + y
This is because according to the algorithm applied, what we are doing is, we are considering the n=1 as 1 set of balanced brackets, like here when we called the function by passing value 6, the output was for where total brackets were 6 and not 6 set of balanced brackets.
So, either you can use same algorithm and call by passing n/2 to get the required result because here we always have to balance the brackets, and in python 3 you also have to type cast if you want it as int later.
But make sure n is even because if n is odd then the balancing will not complete.
I am also providing you a snapshot of my algorithm where I have solved this problem, using recursion I have done. You can add the last few lines that is (Line of code) - 26,27 from the below snapshot if your output is correct but for 2*n.
(These lines will solve the problem, note this is "PYTHON 3".)
I have shown the output by
using n=6 and printing according to the requirement.
The question is in the commented part. The problem is My code always return the result...