Anyone want a challenge? Python: List Comprehension


I have two samples of code below that use list comprehension in lieu of loops because the conversion to bytes is faster by far than loops and when this is called over 40k times per match it is a serious reduction in time.

Here are the times for each function.

Example B runs in approx 1.001 sec for roughly 60 moves computed.
Example A runs in approx 2.347 sec for the same 60ish moves.

Now for the challenge, why does example a take roughly 2.3 times to compute the same data and give the same results that example b does?

(Hint: It might be the way each is structured. IE in what order things are called.)

Good luck figuring it out!

This is the function def,

def __check_delta_moves(self, coord, magnitude):

Example: A

 return [cords for cords in
             [(coord[0] + (c_x * mag), coord[1] + (c_y * mag))
              for mag in range(1, magnitude) if (coord[0] + (c_x * mag), coord[1] + (c_y * mag)) in self._moves_left
             ] for c_x, c_y in self.__delta_move
         ] if magnitude == len(cords) + 1

Example: B

to_move = [possible_move for possible_move in
           [move for move in
                [(coord[0] + (c_x * mag), coord[1] + (c_y * mag))
                 for mag in range(1, magnitude)]
                for c_x, c_y in self.__delta_move] if coord in self._moves_left]
           if magnitude == len(possible_move+1)]
return to_move

It may look like a mess but I will tell you it does the job in 1/5 to 1/80th the time it takes the for/while loops to do the same computations.


I should tell you the functions purpose is to find all the adjacent moves(n,s,e,w) of a given cord up to a given magnitude.


W = (5, 5) = E


Very nice ! Love challenges. Maybe the site should propagate this idea more.