Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I ended up implementing most of this as an exercise.</p> <p>First, find the number of possible locations to split: the number of non-function nodes.</p> <pre><code>def count(obj): total = 0 for o in obj[1:]: # Add the node itself. total += 1 if isinstance(o, list): total += count(o) return total </code></pre> <p>Then, a helper: given an index in the above range, figure out where it is.</p> <pre><code>def find_idx(tree, idx): """ Return the node containing the idx'th function parameter, and the index of that parameter. If the tree contains fewer than idx parameters, return (None, None). """ if not isinstance(idx, list): # Stash this in a list, so recursive calls share the same value. idx = [idx] for i, o in enumerate(tree): # Skip the function itself. if i == 0: continue if idx[0] == 0: return tree, i idx[0] -= 1 if isinstance(o, list): container, result_index = find_idx(o, idx) if container is not None: return container, result_index return None, None </code></pre> <p>Doing the swap is pretty simple now:</p> <pre><code>def random_swap(tree1, tree2): from random import randrange pos_in_1 = randrange(0, count(tree1)) pos_in_2 = randrange(0, count(tree2)) parent1, idx1 = find_idx(tree1, pos_in_1) parent2, idx2 = find_idx(tree2, pos_in_2) # Swap: parent1[idx1], parent2[idx2] = parent2[idx2], parent1[idx1] c = 1 tree1 = ["f:2", c, ["f:1", c]] tree2 = ["f:2", ["f:2", ["f:2", c, c], ["f:2", c, c]], ["f:3", ["f:4", c, c, c, c], ["f:2", c, c], c]] while True: random_swap(tree1, tree2) print tree1 print tree2 </code></pre> <p>This doesn't implement a max depth, but it's a start.</p> <p>This will also never replace the root node, where a node in tree1 becomes the new tree2 and all of tree2 becomes a node in tree1. A workaround would be to wrap the whole thing in eg. [lambda a: a, tree], so editable nodes always have a parent node.</p> <p>This isn't very efficient. Maintaining node counts could make it faster, but then you'd need to store a reference to the parent, too, in order to update the counts efficiently. If you go that route, you'll really want to find or implement a real tree class.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload