Question: In python I need a function that takes an integer and returns the absolute value of n minus the nearest [triangle number](http://en.wikipedia.org/wiki/Triangular_number) to n. The way I'm doing it now is by generating a list of all the triangle numbers up to n. 
Then using:

```
def closest(myList, myNumber):
    c = min(myList, key=lambda x:abs(x-myNumber))

```

To find the closest triangle number. 

The end result list should look like:

```
[0, 0, 1 , 0 , 1 ,1 , 0 , 1, 2 , 1, 0 , 1, 2, 2, 1, 0, etc.]

```

If you have another method of generating the same result that's faster go for it.

Answer: 
You can leverage the *triangle-root* property to quickly calculate the nearest triangle number to a number, and from there easily calculate your value

```
from math import sqrt

def triangle_number(tnumber):
    '''
    returns the tnumberth triangle number (I.E 3 = 6)
    '''
    return (tnumber*(tnumber+1))/2

def triangle_root(number):
    '''
    returns the triangle root of a number (I.E 6 = 3)
    '''
    return (sqrt(8*number+1)-1)/2

def nearest_root(number):
    '''
    Calculates the nearest whole triangle root to a number (I.E. 5 = 3)
    '''
    t_root = triangle_root(number)
    return round(t_root)

def find_delta(number):
    '''
    Given a number, returns abs(n-nearest_triangle)
    '''
    return abs(number - triangle_number(nearest_root(number)))

```

Of course you could condense this into a single function for efficiency, I just spaced it out for clarity.
May not be the best way but should be faster than your method:

```
def triangle_around(n):
    k = int((2*n)**0.5)
    p = (k**2 + k) / 2 
    while p < n:
        k, p = k + 1, p + k + 1 
    return (p - k, p)

def close_triangle(n):
    t = triangle_around(n)
    return min(t[1] - n, n - t[0])

print close_triangle(8)    # gives 2

```