(Nov-17-2019, 09:31 PM)DreamingInsanity Wrote: It's very similar to this:
myList = [6,6,10,50,24,457,24] myNumber= 9 a = min(myList, key=lambda x:abs(x-myNumber)) print(a)(which would return 10)
but instead with arrays.
How can I do this?
To use
min
, was already the right way, also the use of abs
. The key
is used to get for each element one or more values to compare.def find_closest(x, array2d): x_sum = sum(x) ### diffs = [sum(y) - x_sum for y in array2d] print(diffs) # just for demonstration ### result = min(array2d, key=lambda z: abs(sum(z) - x_sum)) index = array2d.index(result) return index, resultIf you don't need the index and the debugging information, the function looks like this.
def find_closest(x, array2d): x_sum = sum(x) return min(array2d, key=lambda z: abs(sum(z) - x_sum))For fun you can implement other functions for comparison.
If the lists are for example points, you can calculate the longest and shortest distances to other points:
x1, y1, z1 = 4, 5, 9 x2, y2, z2 = 40, 50, 90 dist = math.sqrt( (x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2 )With Python 3.8 we got some nice changes in the math module.
For example the hypot function accepts now more than two arguments.
hypot(*coordinates) -> value Multidimensional Euclidean distance from the origin to a point. Roughly equivalent to: sqrt(sum(x**2 for x in coordinates)) For a two dimensional point (x, y), gives the hypotenuse using the Pythagorean theorem: sqrt(x*x + y*y). For example, the hypotenuse of a 3/4/5 right triangle is: >>> hypot(3.0, 4.0) 5.0 Type: builtin_function_or_methodWith this function, it's a bit lesser code:
dist2 = math.hypot(x2-x1, y2-y1, z2-z1)And to calculate distances between points, we've now a convenience function.
Signature: math.dist(p, q, /) Docstring: Return the Euclidean distance between two points p and q. The points should be specified as sequences (or iterables) of coordinates. Both inputs must have the same dimension. Roughly equivalent to: sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) Type: builtin_function_or_methodUsing the function:
point1 = (x1, y1, z1) point2 = (x2, y2, z2) dist3 = math.dist(point1, point2)Instead of using
sum
to calculate the sum of the list, you could use key=lambda z: math.dist(x, z)
.By the way, Python is also very useful to solve homework with code, which the teacher could understand.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!