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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Krishna Deepak
  • 1,735
  • 2
  • 20
  • 31

2 Answers2

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

jabaldonedo
  • 25,822
  • 8
  • 77
  • 77
  • 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 Jul 13 '13 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 – Krishna Deepak Jul 13 '13 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
Eli Rose
  • 6,788
  • 8
  • 35
  • 55