Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a version in python (versions 2 and 3):</p> <pre><code>def aggregate(data): data.sort() i = 0 while i &lt; len(data) - 1: while i &lt; len(data) - 1 and data[i][1] &gt;= data[i+1][0]: data[i] = (data[i][0], max(data[i][1], data[i+1][1])) data.pop(i+1) i += 1 if __name__ == '__main__': itervals = [(1,2), (5,7), (9,12), (3,4), (5,6), (13,17)] formatted = lambda vals: '[{}]'.format(', '.join('({}-{})'.format( iterval[0], iterval[1]) for iterval in sorted(vals))) print(formatted(itervals)) aggregate(itervals) print(formatted(itervals)) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>[(1-2), (3-4), (5-6), (5-7), (9-12), (13-17)] [(1-2), (3-4), (5-7), (9-12), (13-17)] </code></pre> <p>Note: this mutates a list of tuples in-place. A slightly more generic one, that will work with a list of iterables can be done by changing the line:</p> <pre><code>data[i] = type(data[i])((data[i][0], max(data[i][1], data[i+1][1]))) </code></pre> <p>Alternatively, if you know you have a list of mutable iterables, you could use:</p> <pre><code>data[i][1] = max(data[i][1], data[i+1][1]) </code></pre> <p>An alternative version, that may be a little easier to follow, is:</p> <pre><code>def aggregate(data): if not data: return data inputs = sorted(data) result = [inputs[0]] for next0, next1 in inputs[1:]: last0, last1 = result[-1] if next0 &lt;= last1: result[-1][1] = max(next1, last1) else: result.append([next0, next1]) return result </code></pre> <p>Note that this one is designed for a list of lists.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload