Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python closest value to n in list

def closest(arr, target):
  #1: calculate the delta between the number and the target for each numer (this is done in the list comprehension)
  #2: enumerate them to get the index of the minimum
  #2.1: key=... is used because now we have a tuple (check enumerate docs) so, knowing that x[0] is the index, we chose x[1], which is the actual value
  #3 once we have the index use it to access the correct value in the original array
  return arr[min(enumerate([abs(target-x) for x in arr]), key=lambda x: x[1])[0]]


def closest_with_bias(arr, target):
  # this time we will do the same thing but we will have a bias towards numbers above or below the target
  # for example if target is 0 then we can favor positive or negative numbers based on the POSITIVE_BIAS value
  # differences:
  # in the key function we add POSITIVE_BIAS to the calculated delta after checking if x is greater or equal than the target
  # example:
    # arr = [-4, 4, 5]
    # target = 0
    # calculated delta array = [4.1, 4, 5]
    # min will then find the 4 which has index 1
    # we have now favored 4 instead of -4
  POSITIVE_BIAS = .1
  bias = lambda x: abs(target-x[1]) if x[1]>=target else abs(target-x[1])+POSITIVE_BIAS
  return arr[min(enumerate([bias(x) for x in arr]), key=bias)[0]]
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #python #closest #list
ADD COMMENT
Topic
Name
7+7 =