Find a certain difference between members of a list (or set) of numbers
<p>my first question, so please be gentle, I hope I get the formatting right :) I think the question is self explaining. I am looking for a better/faster way to find a difference in a set of numbers... maybe I want a tolerance with it. All I came up with is:</p>

<pre><code> def difference(numbers,diff,tol):
    '''diff is the searched difference,numbers is a list \
    of numbers and tol the tolerance'''
    numbers.sort()
    match=set()
    for i in numbers:
        low = i+diff-tol
        high= i+diff+tol
        for k in numbers:
                if k &gt; high:
                    break
                if k &lt; low:
                    continue
                match.add(i)
                match.add(k)
    return match
</code></pre>

<p>But I bet there are way better ways to achieve the result.</p>

<p>Any idea is welcome,</p>

<p>Christian</p>

<p>You could avoid running the lowest part of the numbers in the second loop (no need for <code>low</code>, just check numbers ahead)</p>

<p>With that you can drop the <code>set</code> and use a <code>list</code> instead: less hashing, less processing. Also, don't change the <code>numbers</code> input by sorting it, the caller may not expect it. Use a locally sorted list instead (the other advantage is that <code>numbers</code> can now be a <code>set</code>, a <code>deque</code> ...:</p>

<pre><code>def difference(numbers,diff,tol):
    '''diff is the searched difference,numbers is a list
    of numbers and tol the tolerance'''
    snum = sorted(numbers)
    match=list()
    for i,n in enumerate(snum):
        high= n+diff+tol
        for j in range(i+1,len(snum)):
                k = snum[j]
                if k &gt; high:
                    break
                match.append(n)
                match.append(k)
    return match
</code></pre>

<p>(maybe that would be a better question for code review, the boundary is thin)</p>

python