Skip to content

Instantly share code, notes, and snippets.

@abunsen
Forked from igorgue/get_aprox.py
Created June 7, 2012 01:16
Show Gist options
  • Save abunsen/2885904 to your computer and use it in GitHub Desktop.
Save abunsen/2885904 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Create a program that given a requested number gives you
the nearest number in a list.
Considerations:
- The list needs to only contain integers
This example is useful when you have only a certain number of
images sizes available and you have to pick one for your station
collage.
e.g.:
>>> requested_size = 21
>>> sizes = (1, 2, 3, 19, 29, 10, 22, 3)
>>> main(requested_size, sizes)
22
"""
def gor(requested_size, sizes):
def get_nearest_distance(previous, current):
distance = abs(requested_size - current)
if distance < previous[1]:
return (current, distance)
else:
return previous
# Calculate the first one, ommit it from the list
first = (sizes[0], abs(requested_size - sizes[0]))
if first[1] == 0:
return first
return reduce(get_nearest_distance, sizes[1:], first)[0]
def javier(requested_size, sizes):
sizes.append(requested_size)
sizes.sort()
req_index = sizes.index(requested_size)
distance1 = abs(sizes[req_index] - sizes[req_index - 1])
distance2 = abs(sizes[req_index] - sizes[req_index + 1])
if distance1 <= distance2:
return sizes[req_index - 1]
else:
return sizes[req_index + 1]
def auston(requested_size, sizes):
return min([(abs(requested_size-x), x) for x in sizes])[1]
def main(requested_size, sizes):
"""
>>> requested_size = 120
>>> sizes = [33, 50, 52, 75, 100, 175, 180, 182, 200, 350]
>>> main(requested_size, sizes)
100
"""
# Test here with:
# return function_name(requested_size, sizes)
raise NotImplementedError('Your code here')
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment