Reputation: 341
With a list of tuple pairs n=[(266, 116), (81, 296), (148, 115), (324, 303)]
I am trying to efficiently find the index of the left-most points. Currently, my code looks like this:
min_index = 0
for i in range(1,len(n)):
if points[i][0] < points[min_index][0]:
minIndex = i
but to me this does not look efficient. I also found a solution using lambda function, which might at least look more appealing (idk about the time complexity here of the min function)
min(n, key = lambda t: t[0])
but this gives me the actual coordinates, not the index which I want. How can I change the lambda function to give me the actual index, and is there any better solution in terms of time complexity? Thank you
Upvotes: 0
Views: 577
Reputation: 9580
You could also enumerate
in the lambda
part to get both the index and the value as:
n = [(266, 116), (81, 296), (148, 115), (324, 303)]
min_index, min_value = min(enumerate(n), key = lambda n: n[1][0])
print(min_index, min_value) # 1 (81, 296)
Upvotes: 0
Reputation: 22776
Use range(len(n))
in the min
instead of n
:
>>> min(range(len(n)), key = lambda i: n[i][0])
1
Note: the loop approach is not in anyway inefficient since there is no apparent pattern in the data, so you can't, for instance, use a dichotomy approach (such as binary search), and the min
does almost the same thing, it's just preferred sometimes because it is built-in, more concise, and less prone to errors.
Upvotes: 1