4

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

3
  • Does it have to be one line? I think you're shooting yourself in the foot a bit on that one. Commented Nov 17, 2014 at 21:54
  • I think he means in one loop iteration, but yes, OP, if you could clarify. Commented Nov 17, 2014 at 21:57
  • @FrankV Well, he states "in the same iteration, in one line," so I'm assuming he means it literally. I think he's barking up the wrong tree, but that appears to be the tree in question. Commented Nov 17, 2014 at 21:58

2 Answers 2

7

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())
Sign up to request clarification or add additional context in comments.

4 Comments

Dam you beat me to it
can you explain me about float('inf') and float('-inf') . what the use of it.
@Hackaholic: float infinity values are guaranteed to be larger or smaller than any other number. So min_value is set to float('inf') and any other number is smaller than that, however large you make it.
@MartijnPieters +1 for float('inf') concept :)
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.