get the sum of differences between integers in a list

John Pote johnpote at jptechnical.co.uk
Tue Sep 20 19:19:56 EDT 2016


On 20/09/2016 12:52, Daiyue Weng wrote:

> Hi, I have a list numbers say,
>
> [1,2,3,4,6,8,9,10,11]
>
> First, I want to calculate the sum of the differences between the numbers
> in the list.
At least for this first part a little pencil, paper and algebra yields a 
simple formula of constant and minimal calculation time. I had an 
intuitive guess and wrote down the sum of differences for a couple of 
examples,
[1, 2, 5]       => 4
[9, 11, 17, 19] => 10
It works for negative differences as well,
[1, 2, 5, 1]    => 0
The trick is to spot the relation between the sum of differences and the 
numbers in the list. A few lines of algebra then gave a very simple formula.

As for the rest it's down to code as others have hinted at.
> Second, if a sequence of numbers having a difference of 1, put them in a
> list, i.e. there are two such lists,
>
> [1,2,3]
>
> [8,9,10,11]
>
> and also put the rest numbers in another list, i.e. there is only one such
> list in the example,
>
> [6].
>
> Third, get the lists with the max/min sizes from above, i.e. in this
> example, the max list is,
>
> [8,9,10,11]
>
> min list is
>
> [1,2,3].
>
> What's the best way to implement this?
>
> cheers




More information about the Python-list mailing list