help - iter & dict
John Machin
sjmachin at lexicon.net
Thu Aug 3 17:55:12 EDT 2006
Something strange possessed Tim Chase and caused him to write:
> def findClosest(dataset, target):
[subtly *BUGGY* and overly verbose]
> def findClosest2(dataset, target):
[evil]
Try this (tested to the extent shown):
C:\junk>type dict_closest.py
def findClosest(dataset, target):
[snip]
def findClosest2(dataset, target):
[snip]
def findClosest3(dataset, target):
closest_value = closest_key = closest_distance = None
for k, v in dataset.items():
distance = (target - v) ** 2
# or use abs(target - v)
if (closest_value is None
or distance < closest_distance):
closest_key = k
closest_value = v
closest_distance = distance
return closest_key, closest_value
if __name__ == '__main__':
for testno, test in enumerate([
(4, {'a':1, 'b':3, 'c':6}),
(0.1, {'a':0, 'b':3}),
(0.1, {'a':3, 'b':0}),
]):
target, data = test
print
for func in findClosest, findClosest2, findClosest3:
k, v = func(data, target)
print "test:%d func: %-13s -> %r %r" \
% (testno + 1, func.__name__, k, v)
C:\junk>dict_closest.py
test:1 func: findClosest -> 'b' 3
test:1 func: findClosest2 -> 'b' 3
test:1 func: findClosest3 -> 'b' 3
test:2 func: findClosest -> 'b' 3 <<<<<<=======
test:2 func: findClosest2 -> 'a' 0
test:2 func: findClosest3 -> 'a' 0
test:3 func: findClosest -> 'b' 0
test:3 func: findClosest2 -> 'b' 0
test:3 func: findClosest3 -> 'b' 0
HTH,
John
More information about the Python-list
mailing list