0

First of all I need to use map function in python and not comprehensions to implement multiprocessing.

My initial version of a list comprehension is as follows

t3List = [x for x in rowCost if ( cost[t1][t2]+cost[rowCost.index(x)][tour[ tour.index(rowCost.index(x)) - 1 ] ]-cost[t2][rowCost.index(x)]-cost[t1][tour[ tour.index(rowCost.index(x)) - 1 ] ]>0 and rowCost.index(x) !=t1 and rowCost.index(x) != t2 and rowCost.index(x) != tour[ tour.index(t2)+1]  and x<cost[t1][t2] ) ]

For more understanding t1 and t2 are just vertices. eg values of t1,t2 are 34,21 respectively. rowcost is a list which contains distances from one vertex to every other vertex.

tour is just some order of vertices in which I have to travel ( basically I m solving tsp )

Here all variables are local. cost is like just a symmetric cost matrix of all vertices.

For huge number of vertices this list is taking 0.5 to 1 sec to compute. So I planned to implement multiprocessing after seeing this

I understood that map function takes first argument as a function.

But to implement above comprehension this function has to have multiple parameters as all the variables are local.

How to solve this problem? Any help hugely appreciated.

2 Answers 2

1

Try this code:

def f(rowCost, x, cost, t1, t2, tour):
    if cost[t1][t2]+cost[rowCost.index(x)][tour[ tour.index(rowCost.index(x)) - 1 ] ]-cost[t2][rowCost.index(x)]-cost[t1][tour[ tour.index(rowCost.index(x)) - 1 ] ]>0 and rowCost.index(x) !=t1 and rowCost.index(x) != t2 and rowCost.index(x) != tour[ tour.index(t2)+1]  and x<cost[t1][t2]:
        return x
    else:
        return None

t3List = filter(None, map(f, rowCost))

I'm assuming that any value of rowCost can't value None in order to reduce the map resulto with filter

2
  • 1
    I don't believe this will work, because the function f takes multiple arguments and the map call only gives it rowCost to work with.
    – Eli Rose
    Commented Jul 13, 2013 at 15:08
  • the above solution gives me a error and is completely wrong. I mentioned this in my question too that f is a function which takes only one argument i.e x Commented Jul 13, 2013 at 22:28
0

I think what you want is jabaldonedo's answer, except instead of the function f taking in x, cost, t1, t2, tour those values should be defined elsewhere and it should just reference them. i.e. your function should be "curried" from a function of many arguments into a function of one.

def f(rowCost):
    if <huge boolean expression>:
        return x
    else:
        return None

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.