Given [1,2,3,4,5]
, how can I do something like
1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5
I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return (1,5)
.
So basically I would like to do something like
for each element i
in the list
map some function across all elements in the list, taking i
and j
as parameters
store the result in a master list, find the minimum value in the master list, and return the arguments i
, j
used to calculate this minimum value.
In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.
If I'm correct in thinking that you want to find the minimum value of a function for all possible pairs of 2 elements from a list...
Doing it the mathy way...
Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.
If working with Python ≥2.6 (including 3.x), you can:
EDIT: Now that I think of it and if I remember my mathematics correctly, this should also give the answer assuming that all numbers are non-negative:
You can do this using list comprehensions and min() (Python 3.0 code):
Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do
from __future__ import division
so that 1/5 correctly equals 0.2 instead of 0.Some readable python:
Let me know if something is not clear.
If you don't mind importing the numpy package, it has a lot of convenient functionality built in. It's likely to be much more efficient to use their data structures than lists of lists, etc.