1

I have a method and as an argument I enter x and y coordinates of a point and then I calculate the power reached to that [x,y] coordinate from other points and sort them in order of highest power reached to lowest:

def power_at_each_point(x_cord, y_cord):
    nodez_list = [nodes_in_room for nodes_in_room in range(1, len(Node_Positions_Ascending) + 1)]
    powers_list = []
    for each_node in nodez_list:
    powers_list.append(cal_pow_rec_plandwall(each_node, [x_cord, y_cord]))
    return max(powers_list)

I want to do that in a more pythonic way like key = cal_pow_rec_plandwall but this method takes two arguments and not one. So how can I do it?

Mahmoud Ayman
  • 197
  • 1
  • 13

1 Answers1

1

You just need a single call to max which takes a generator as an argument. The lambda expression is just to make things more readable.

def power_at_each_point(x_cord, y_coord):
    f = lambda x: cal_pow_rec_plandwall(x, [x_coord, y_coord])      
    return max(f(each_node) for each_node in xrange(1, len(Node_Positions_Ascending) + 1))

You can replace the generator with a call to itertools.imap:

from itertools import imap

def power_at_each_point(x_coord, y_coord):
    f = lambda x: cal_pow_rec_plandwall(x, [x_coord, y_coord])
    return max(imap(f, xrange(1, len(Node_Positions_Ascending) + 1)))
chepner
  • 497,756
  • 71
  • 530
  • 681
  • At no point do you actually need all the values; `max` just needs to look at them one at a time and keep the largest it has seen to date. In Python 2, this saves building the entire list up front; in Python 3, the built-in `map` will work fine. – chepner May 03 '15 at 17:22
  • (For the same reason I just changed `range` to `xrange` for use in Python 2.) – chepner May 03 '15 at 17:24