2

I would like know how I can find the nearest solution.

For example, I have a list like it :


list=[1,2,3,4,5,6,7]   

And ofc my list is really big , and I want find the nearest solution.

If I say at my algorithm, " find me the number 8" But I have no number 8, so he will return me 7 because 7 is the nearest from 8.

Thanks for reading me !

john
  • 9
  • 4
  • Does this answer your question? [from list of integers, get number closest to a given value](https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value) – Joe Sep 19 '20 at 13:38

2 Answers2

2
min(list, key= lambda x: abs(solution - x))

this code returns the object in his list that his abs distance from the solution is the smallest.

Tomer Shinar
  • 415
  • 3
  • 13
1

Try this :

my_list=[1,2,3,4,5,6,7]

target = 8
dist = [abs(i - target) for i in my_list]
min_index = dist.index(min(dist))
print(my_list[min_index])
AmirHmZ
  • 516
  • 3
  • 22