Sunday 15 March 2015

algorithm - What python code generates all possible groupings (trees) for binary operators -


As explained in many SO queries, and in a nutshell, the sequence of Catalan numbers corresponds to the number of parenthetical groupings That can be generated for any given operators but I have not got an algorithm for generating all these groups.

This matches the binary braking algorithm and it can be described in many different ways. The most obvious practical use for this algorithm is to generate all possible expressions by binary operators around each potential braking and the number that runs on them. It can be used to test various types of operations on binary trees.

Web search has come to know, but I think it will take some time to understand me because I do not know C # syntax.

Then, Python generates all possible groups of brackets around code operators (which can thus be used with actual expression to generate all possibilities in this way)? For output 2, 3 and 4, will look like:

AllBinaryTrees (2)

  1. (x (xx))
  2. (xx) X X (x)

    AllBinaryTrees (3)

    1. (xx) x) x
    2. ) X (x Xx) x) xx (xx) x (xx) x)
    3. AllBinaryTrees (4)

    4. (x (x (x (x (xx)) x))
    5. (Xx (xx))
    6. (Xx (xx) x)
    7. ((xx) (x (xx))
    8. (Xx) (xx) x))
    9. ((x (xx)) (xx))
    10. ((xx) x) (xx))
    11. (x (xx) x)) x
    12. (xx) (xx)) x
    13. (<(x (xx)) x)
    14. (((xx) x) x

      even more Better code will do something like the following:

      AllBinaryTrees ("2 + 3/4")

      Output:

      1. 2+ (3 / 4)
      2. (2 + 3) / 4

        How about < / P>

          def allbinarytrees (s): if lane (s) == 1: yield s other: for the category i (1, lane, 2): allbinarytrees for l (s [: i] ): For subbintrates in R (S [i 1:]): produce '({} {} {})' Sample (L, S [i], r)   

        Sample usage:

          T: print (t)   

        Output:

          (1 + (2- (3 * (4/5)) (1+ ( 2 - (3 * 4) / 5)) (1 + ((2-3) * (4/5))) (1 + ((2- (3 * 4)) / 5)) (1 + ((2-3) * 4) / 5)) ((1 + 2) - (3 * (4/5))) ((1 + 2) - ((3 * 4) / 5)) ((1 + (2-3)) * (4/5)) (((1 + 2) -3) * (4/5)) ((1 + (2- (3 * 4)) / 5) ((1 + ((2-3) * 4)) / 5) ((1 + 2) - (3 * 4)) / 5) (((1 + (2-3)) * 4) / 5) (( (1 + 2) -3) * 4) / 5)    

No comments:

Post a Comment