Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Recursive backtracking function: how to clear variables on new function call?

I've been trying to write a simple function to make lists of all the Young diagrams/partitions between a starting partition ('top') and an ending partition ('bot'), with each step in the list a covering relation (exactly one box difference in each step).

For instance, I would like to input [2,1] for top and [1] for bot and get

[[2,1],[2],[1]]

[[2,1],[1,1],[1]]

as my outputs. (I want to do this because it's useful for some computations with Littlewood-Richardson coefficients; having the lists that give each partition in a path between top and bot will be useful for other computations.)

My code at present has an echo, and worse, I can't figure out where to initialize path_list. Where do I put path_list = [] -- or create other lists -- to make sure that:

  1. I get a separate list for each path, and
  2. Calling the function again clears path_list?

(2) is worst: right now, since path_list is an internally-defined variable, I get the following bad behavior:

sage: load "makepartitionlist.sage"

sage: get_path([1],[1])

[[1]]

[[1]]

sage: get_path([1],[1])

[[1], [1]]

[[1], [1]]

sage: get_path([1],[1])

[[1], [1], [1]]

[[1], [1], [1]]

because path_list is not cleared when I call get_path again (which I'd hoped putting path_list = [] in the arguments would accomplish).

The code:

def get_path(top, bot, path_list = []):
    path_list.append(top)
    if top == bot:
       print path_list
       return path_list
    if not Partition(top).contains(Partition(bot)):
       return None
    for i in range(0,len(Partition(top).down_list())):
            p = Partition(top).down_list()[i]
        if Partition(p).contains(bot):
           path_list.append(p)
           get_path(p, bot, path_list)

I'm using Sage 5.0.1 with Sage-combinat providing the Partition function and others.