Hi Guys

What i am trying to do here is have a tuple of numbers, lets say X. Then i have a list of a few other tuples. I want the program to find the tuple that is closest in value.

x = (214,521)
lis = [(200,500),(250,550),(300,600)]

I am doing this becuase i want to find where a person clicks on screen and then work out which function to run by finding which one in the list the person clicked closest to. Im having trouble getting started here so any help would be greatly appreciated.

10 Years
Discussion Span
Last Post by vegaseat

Something like this might work ...

x = (214, 521)
q = [(200, 500),(250, 550),(300, 600)]

t = []
for item in q:
    #print item
    a = abs(item[0]-x[0])
    b = abs(item[1]-x[1])
    avg = (a + b)/2.0
    t.append((avg, item))

# the closest is ...
print min(t)     # (17.5, (200, 500))
print min(t)[1]  # (200, 500)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.