As explained in several SO questions and more abstractly at mathworld , a sequence of Catalan numbers corresponds to the number of brackets that can be generated for any given number of operators. But I did not find an algorithm to generate all these groups.
This binary bracketing algorithm follows Tamari Lattice and can be described in several ways. The most obvious practical application of this algorithm is the generation of all possible expressions by all possible brackets around binary operators and the numbers on which they work. This can be used to exhaustively test various types of binary tree operations.
A web search revealed one implementation in C # , but I think it would take me some time to understand, since I don't know the C # syntax.
So, what python code generates all possible groupings of parentheses around statements (which, thus, can be used with the actual expression to generate all the possibilities)? The result will look like this for 2, 3, and 4:
AllBinaryTrees (2)
AllBinaryTrees (3)
- (((xx) x) x)
- ((x (xx)) x)
- ((xx) (xx))
- (x ((xx) x))
- (x (x (xx)))
AllBinaryTrees (4)
- (x (x (x (xx))))
- (x (x ((xx) x)))
- (x ((xx) (xx)))
- (x ((x (xx)) x))
- (x (((xx) x) x))
- ((xx) (x (xx)))
- ((xx) ((xx) x))
- ((x (xx)) (xx))
- (((xx) x) (xx))
- ((x (x (xx))) x)
- ((x ((xx) x)) x)
- (((xx) (xx)) x)
- (((x (xx)) x) x)
- (((((xx) x) x) x)
Even better would be code that would do something like the following:
AllBinaryTrees ("2 + 3/4")
output:
source share