I have the following code:
max=max(len(j.links) for j in roads.junctions())
min=min(len(j.links) for j in roads.junctions())
roads.junctions() returns a list with almost 1 million junctions. Is there a way to find the minimum and the maximum of the items in the same iteration, in one line (instead of writing a function that computes them both)?
You can't get both the minimun and maximum in one line, but you can get them with a simple loop:
min_value, max_value = float('inf'), float('-inf')
for j in roads.junctions():
value = len(j.links)
if value < min_value:
min_value = value
if value > max_value:
max_value = value
This produces the values with the same complexity as min()
and max()
: O(N), so linear complexity. It also looks at each value in isolation, not requiring all values to be in a single list in memory.
You can always wrap that into a function of course:
def min_and_max(iterable):
min_value, max_value = float('inf'), float('-inf')
for value in iterable:
if value < min_value:
min_value = value
if value > max_value:
max_value = value
return min_value, max_value
min_value, max_value = min_and_max(len(j.links) for j in roads.junctions())
the necessary reduce
one-liner (just because it is doable in one line):
min_v, max_v = reduce(lambda y,x: (min(len(x), y[0]), max(len(x), y[1])), roads.junctions(), (float('inf'), float('-inf')))
The lambda takes a argument that has a length, and a tuple of current min/max, and returns the updated tuple. The tuple is initialized with inf/-inf, and the lambda is applied to all items of the iterable passed to reduce
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With