mylist = [1, 2, 3, 4, 5, 6, 7, 9, 10]
mynumber = 8
I want to find the number in the list closest to mynumber. How can I write a function that can do that?
I'm still a beginner, so how can I do it with only loops and if
statments?
mylist = [1, 2, 3, 4, 5, 6, 7, 9, 10]
mynumber = 8
I want to find the number in the list closest to mynumber. How can I write a function that can do that?
I'm still a beginner, so how can I do it with only loops and if
statments?
Considering you want closest minimum value . You can try min function also :
min(myList, key=lambda x:abs(x-myNumber))
Update:
You can also go with this:
mylist = [1, 2, 3, 4, 5, 6, 7, 9, 10]
mynumber = int(raw_input("enter num : "))
def closest(list, Number):
temp = []
for i in list:
temp.append(abs(Number-i))
return temp.index(min(temp))
a = closest(mylist, mynumber)
print "index is : ",a
print "Closet value is : ",mylist[a]
Iterate over the list and compare the current closest number
def takeClosest(myList, myNumber):
closest = myList[0]
for i in range(1, len(myList)):
if abs(i - myNumber) < closest:
closest = i
return closest