How to put sequential numbers into lists from a list
<p>I have a list numbers say,</p>

<p><code>[1,2,3,6,8,9,10,11]</code></p>

<p>First, I want to get the sum of the differences (step size) between the numbers <code>(n, n+1)</code> in the list.</p>

<p>Second, if a set of consecutive numbers having a difference of 1 between them, put them in a list, i.e. there are two such lists in this example,</p>

<p><code>[1,2,3]</code></p>

<p><code>[8,9,10,11]</code></p>

<p>and then put the rest numbers in another list, i.e. there is only one such list in the example,</p>

<p><code>[6]</code>.</p>

<p>Third, get the lists with the max/min sizes from the sequential lists, i.e. <code>[1,2,3]</code>, <code>[8,9,10,11]</code> in this example, the max list is,</p>

<p><code>[8,9,10,11]</code></p>

<p>min list is</p>

<p><code>[1,2,3]</code>.</p>

<p>What's the best way to implement this?</p>

<p>I wonder if you've already got the answer to this (given the missing 4 from your answers) as the first thing I naively tried produced that answer. (That and/or it reads like a homework question)</p>

<pre><code>&gt;&gt;&gt; a=[1,2,3,4,6,8,9,10,11]
&gt;&gt;&gt; sum([a[x+1] - a[x] for x in range(len(a)-1)])
10
&gt;&gt;&gt; [a[x] for x in range(len(a)-1) if abs(a[x] - a[x+1]) ==1]
[1, 2, 3, 8, 9, 10]
</code></pre>

<p>Alternatively, try :</p>

<pre><code>a=[1,2,3,6,8,9,10,11]
sets = []
cur_set = set()
total_diff = 0
for index in range(len(a)-1):
    total_diff += a[index +1] - a[index]
    if a[index +1] - a[index] == 1:
        cur_set = cur_set | set([ a[index +1], a[index]])
    else:
        if len(cur_set) &gt; 0:
            sets.append(cur_set)
        cur_set = set()

if len(cur_set) &gt; 0:
    sets.append(cur_set)

all_seq_nos = set()
for seq_set in sets:
    all_seq_nos = all_seq_nos | seq_set
non_seq_set = set(a) - all_seq_nos

print("Sum of differences is {0:d}".format(total_diff))

print("sets of sequential numbers are :")
for seq_set in sets:
    print(sorted(list(seq_set)))

print("set of non-sequential numbers is :")
print(sorted(list(non_seq_set)))

big_set=max(sets, key=sum)
sml_set=min(sets, key=sum)
print ("Biggest set of sequential numbers is :")
print (sorted(list(big_set)))
print ("Smallest set of sequential numbers is :")
print (sorted(list(sml_set)))
</code></pre>

<p>Which will produce the output :</p>

<pre><code>Sum of differences is 10
sets of sequential numbers are :
[1, 2, 3]
[8, 9, 10, 11]
set of non-sequential numbers is :
[6]
Biggest set of sequential numbers is :
[8, 9, 10, 11]
Smallest set of sequential numbers is :
[1, 2, 3]
</code></pre>

<p>Hopefully that all helps ;-)</p>

python list