Question

The question is in the commented part. The problem is My code always return the result...

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

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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.

Add a comment
Know the answer?
Add Answer to:
The question is in the commented part. The problem is My code always return the result...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT