I have a list.
I want to find out which number in the list is closest to k between highest and lowest but without using lambda
or abs
. How can I do it?
a=[1,5,8,4,9,25,10,16,54]
k=12
highest = max(a)
lowest = min(a)
I have a list.
I want to find out which number in the list is closest to k between highest and lowest but without using lambda
or abs
. How can I do it?
a=[1,5,8,4,9,25,10,16,54]
k=12
highest = max(a)
lowest = min(a)
Try this tricky code,
Code Syntax
for each in sorted(a):
if each < k:
lowest = each
else:
highest = each
break
print(f"Original List: {a}\nLowest according to ({k}): {lowest}\nHighest according to ({k}): {highest}")
Output
Original List: [1, 5, 8, 4, 9, 25, 10, 16, 54]
Lowest according to (12): 10
Highest according to (12): 16
[Program finished]
a=[1,5,8,4,9,25,10,16,54]
k=12
import sys
def func(lis, val):
# minimum_difference is used to check the difference between value in list and key we have and it will keep record of minimum difference
minimum_difference = sys.maxsize
# nearest_value will save the list value for which we got minimum difference
nearest_value = None
# iterating through the list elements
for i in lis:
# getting the difference b/w key value and list element
difference_key_element = val - i
# checking if difference is neagtive or not, if negative make
# it positive
if difference_key_element<0:
difference_key_element *= -1
# checking if minimum value we find so far, is less then the
# current difference b/w key value and element value
# if it is less then the current min value, replace it
# and store the list element in the store variable
if difference_key_element<minimum_difference:
minimum_difference=difference_key_element
nearest_value = i
# return the store variable
return nearest_value
solution = func(a, k)
print(solution)
output
10