pythonRcpp
pythonRcpp

Reputation: 2146

passing list item name as a list type to function

This is a short snippet from my code while solving this problem. I want to push items in the list into stack, but same item name should be used as a list name when passing to run function. My intent is something close to depth first search and base case to stop recursion is to be included soon in my code. Is there any way to cast item popped to be taken as a list name argument.

#Below is dependency list
p1-['p2','p3']
p2=['p3','p4']
p3=['p4']
p4=[]
p5=[]

def run(pro=[])
    if pro: #process has a dependency, push its items dependency into stack
        for dependency in pro:
            stack.push(dependency)
        run(stack.peek) #I need to pass top item of stack as a list

Upvotes: 0

Views: 82

Answers (1)

cdlane
cdlane

Reputation: 41872

Here's an example recursive, dictionary-based approach:

dependencies = { \
    'p1': ['p2', 'p3'], \
    'p2': ['p3', 'p4'], \
    'p3': ['p4'], \
    'p4': [], \
    'p5': [] \
    }

def run_order(process, order=None):

    if order is None:
        order = []

    precursors = dependencies[process]

    if precursors:
        for precursor in precursors:
            run_order(precursor, order)

        if process not in order:
            order.append(process)  # should really be insert after right-most precursor

    elif process not in order:
            order.insert(0, process)  # no dependencies, start ASAP

    return order

print(run_order('p1'))

PRINTS

['p4', 'p3', 'p2', 'p1']

Does this order the processes correctly for your purposes? (You will need to test various scenarios.) Another approach is to allow run_order() to take a list of processes:

def run_order(processes, order=None):

    if order is None:
        order = []

    for process in processes:
        precursors = dependencies[process]

        if precursors:
            run_order(dependencies[process], order)

            if process not in order:
                order.append(process) # should really be insert after right-most precursor

        elif process not in order:
            order.insert(0, process)  # no dependencies, start ASAP

    return order

print(run_order(['p1']))
print(run_order(list(dependencies.keys())))

PRINTS

['p4', 'p3', 'p2', 'p1']
['p5', 'p4', 'p3', 'p2', 'p1']

Again, test various scenarios to decide if it works for your purpose.

Upvotes: 2

Related Questions