I've stumbled across a problem that I'm having trouble figuring out a solution to. I have a list of coordinates, containing both positive and negative values, and I need to find the x-coordinate farthest from zero in the list. This has a pretty simple solution:
foo = max(map(lambda x: abs(x[0]),bar))
where bar is a list of coordinate tuples.
The problem with this is that once I've found the value farthest from zero, I have to preserve its original sign (positive or negative) for later calculation. I can't index foo in bar to find the original value because foo might have been negative in the list and thus would be unable to be indexed. Another possible solution might be:
foo = max(enumerate(bar),key=lambda x: abs(x[1][0]))
and then using the enumeration to find the index of the original value in bar:
bar=[[-1,3],[5,2],[-8,2]]
#bar enumerated: [(0,[-1,3]),(1,[5,2]),(2,[-8,2])]
foo=max(enumerate(bar),key=lambda x: abs(x[1][0]))
#foo = (2,[8,2])
foo = bar[foo[0]]
But I was wondering what other possible solutions might there be to this problem?
EDIT: I should note that bar may be between 10,000 and 100,000 values
Well, it turns out that the simple code:
max(bar, key=lambda x: abs(x[0]))
will actually return the negative value correctly;
bar=[[-1,3],[5,2],[-8,2]]
foo=max(bar,key=lambda x: abs(x[0]))
#foo = [-8,2]
Not sure why I skimmed right over it, I guess I just overestimated the original complexity of the problem.
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