Welcome, guest | Sign In | My Account | Store | Cart

The python code generates balanced parenthesis recursively. Example for depth=3 i.e. 3 opening brackets and 3 closing brackets,the sample output should be:

((())) (()()) (())() ()(()) ()()()

The number of such output ( 5 in above case) is a Catalan Number.

Python, 8 lines
1
2
3
4
5
6
7
8
def pargen(left,right,ans):
    if(left==0 and right==0):
        print ans;
    if(left>0):
        pargen(left-1,right+1,ans+'(');
    if(right>0):
        pargen(left,right-1,ans+')');        
pargen(3,0,''); #can pass any starting value as left,initial value of right is always 0.
Created by bartender on Thu, 14 Feb 2013 (MIT)
Python recipes (4591)
bartender's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks