My Python is a bit rusty and I'm really having trouble with this super simple algorithm.
I'm trying to write a function that takes two parameters (target, values) to find which number in the values is closest to the target number; if there happens to be a tie, then select the lower number.
Here's my progress, but I've only ever selected the lower number without actually comparing the difference of the values in the list in comparison to the relative distance of the target.
So, in essence, my function hasn't actually completed the challenge correctly at all because 47 is actually closer to 46 than 31 is; however, if the numbers contained in the list were hypothetically 45 and 47, then they would be equally distant from my target number and so 45 should be printed and not 47.
I'd prefer answers that use simple for/if/while loops so that I can really practice my skills.
Other more advanced answers are also welcome with a detailed explanation.
EDIT
A few really good answers from you guys, much appreciated; I'm testing them as we speak and will choose the one most fitting to my style and use the rest as references, even if you have the best one-liner answer.
target = 46
values = [1, 22, 31, 47, 87, 99]
def closest_to_target(target, values):
lower = []
for number in values:
if number < target:
lower.append(number)
if lower:
lowest = sorted(lower, reverse=True)[0]
return lowest
else:
return "Error handling array"
print closest_to_target(target, values)