Reputation: 3
I know this can easily be done in a for loop, but I'm thinking there must be an intuitive way to do this in 1 line. For more explanation - you are given two lists, "juice" and "capacity". juice shows how much juice a certain index has and capacity shows the capacity of the index. I'm trying to find the index with the most remaining capacity. So I tried to do that by doing this:
maxCap = max(capacity[i] - juice[i] for i in range (0, N - 1))
But of course this doesn't save the index. How can I assign maxCap to the "i" which produces the maxCap as I have written?
Upvotes: 0
Views: 39
Reputation: 1116
You may use reduce
:
import functools
remainings = [capacity[i] - juice[i] for i in range (0, len(capacity) - 1)]
maxCap = functools.reduce(lambda acc, cur: acc if remainings[acc] > remainings[cur] else cur, range(len(remainings)), 0)
Reduce iterates over the iterable and returns a single result determined by the given reducer function.
Upvotes: 0
Reputation: 19352
maxCap = max(capacity[i] - juice[i] for i in range (0, N - 1))
This same thing can be done simpler this way (although I don't understand the N-1
part, so I am ignoring it):
maxCap = max(c - j for c, j in zip(capacity, juice))
Still, that gives the result, not the index. To find the index, max
has to go through i
values, rather than the calculated results, but maximise the results, like this:
max_index = max(range(N), key=lambda i: capacity[i] - juice[i])
On the other hand, if you are looking for efficiency, this is a good thing for numpy
. If both juice
and capacity
are numpy
arrays, then this can be done:
max_diff = (a - b).max()
max_index = (a - b).argmax()
Upvotes: 1