Organize a list of unique integers and create ranges/summaries when possible
<p>I am trying to setup a function or a class to store unique integers with abilities to add,remove or check for existence. This of course can be easily achieved using normal set. The tricky part here is displaying of ranges. I mean, if I have all the numbers between 100 and 20000 I don't want to display a huge list all the numbers in between, but rather displaying 100-20000. </p>

<p>Consider the following example:</p>

<pre><code>numbers 3000,3008-3015,3020,3022,3030-3043,3068
</code></pre>

<p>The goal is to create a function or class to add, check or retrieve information about current numbers. Here is how I imagine this: </p>

<pre><code>&gt;&gt;&gt; f_check(3016) 
False
&gt;&gt;&gt; f_check(3039)
True
&gt;&gt;&gt; f_add(3016)
3000,3008-3016,3020,3022,3030-3043,3068
&gt;&gt;&gt; f_remove(3039)
3000,3008-3016,3020,3022,3030-3038,3040-3043,3068    
&gt;&gt;&gt; f_add(3100)
3000,3008-3016,3020,3022,3030-3038,3040-3043,3068,3100
</code></pre>

<p>and so forth... </p>

<p>Again, pay attention to the range part (3030-3038, 3040-3043) etc. I don't want to display every single entry for the consecutive numbers but rather displaying a "summary" or range. </p>

<p>Using the same example again, if I add 3021, I'll expect the following result:</p>

<pre><code>&gt;&gt;&gt; f_add(3021)
3000,3008-3016,3020-3022,3030-3043,3068
</code></pre>

<p>Many thanks in advance for your thoughts!</p>

<p>Okay, first of all - thanks everyone for your efforts. Much appreciated.</p>

<p>Here is the solution I ended up with. I have simply used a class to extend a set &amp; modifying the output of it.</p>

<pre><code>class vlans(set):
  def check(self,number):
    if number in self:
        return True
  def __str__(self):
    last = 0
    out = []
    for x in list(self):
        if len(out)&gt;0 and last+1==int(x):
            out[-1] = out[-1].split("-")[0]+"-"+str(x)
        else:
            out.append(str(x))
        last = int(x)
  return ",".join(out)
</code></pre>

<p>And here is how it works:</p>

<pre><code>&gt;&gt;&gt; f=vlans([3008, 3009, 3010, 3011, 3012, 3013, 3014, 
    3015, 3020, 3022, 3030, 3031, 3032, 3033, 3034, 3035, 
    3036, 3037, 3038, 3039, 3040, 3041, 3042, 3000, 3068])
&gt;&gt;&gt; 
&gt;&gt;&gt; 
&gt;&gt;&gt; print f
3000,3008-3015,3020,3022,3030-3042,3068
&gt;&gt;&gt; f.check(3021)
&gt;&gt;&gt; f.add(3021)
&gt;&gt;&gt; f.check(3021)
True
&gt;&gt;&gt; print f
3000,3008-3015,3020-3022,3030-3042,3068
&gt;&gt;&gt; f.remove(3035)
&gt;&gt;&gt; print f
3000,3008-3015,3020-3022,3030-3034,3036-3042,3068
</code></pre>

<p>Apologies for the vague description of what I needed, but hope it all makes sense now!</p>

python integer set