Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding min and max on same iteration in Python

Tags:

python

max

min

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)?

like image 595
Ohad Feder Avatar asked Dec 26 '22 02:12

Ohad Feder


2 Answers

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())
like image 149
Martijn Pieters Avatar answered Dec 27 '22 14:12

Martijn Pieters


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.

like image 31
njzk2 Avatar answered Dec 27 '22 16:12

njzk2