get the sum of differences between integers in a list

Steve D'Aprano steve+python at pearwood.info
Tue Sep 20 10:45:42 EDT 2016


On Tue, 20 Sep 2016 09:52 pm, 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.

Sounds like homework. What have you tried?


Hint: use the sum() function to sum a list of numbers:

py> sum([1, 2, 3])
6

Another hint: to calculate the differences between numbers, you need to look
at each number except the first, and subtract the *previous* number. Or
possibly the *next* number. You decide what the question wants you to do.
One way to do that is to loop over the INDEXES 0, 1, 2, 3, ... up to the
number of items:

for index in range(len(some_list)):
    x = some_list[i]


A third hint (for advanced students): you can use zip() and list slicing to
get the numbers two at a time without using the indexes.



> 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].


Hint: for each number, decide whether or not the difference is 1. If the
difference is *not* one, that's easy: just place that number into a second
list.

If the difference is 1, then you place that number into a third list, BUT
only as part of a run. So you'll go:

difference between 1 and 2 is 1, so 1 goes into list B;
difference between 2 and 3 is 1, so 2 goes into list B;
difference between 3 and 4 is 1, so 3 goes into list B;
difference between 4 and 6 is 2, so 4 goes into list A;
difference between 6 and 8 is 2, so 6 goes into list A;
difference between 8 and 9 is 1, so list B is put aside, 
    a new list is started, and 8 goes into this new list B;

etc.

Hint: try keeping a list of lists. To start a new list, append an empty list
to it.



> 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].


Hint: 

min([5, 6, 4, 1, 2, 3]) returns the smallest number, 1.
max([5, 6, 4, 1, 2, 3]) returns the largest number, 6.

Use len() to get the size of a list.



> What's the best way to implement this?

By writing code, of course! But writing code should be the SECOND thing you
do, not the first.

First, work through the calculation by hand. How do you do it by hand, using
pen and paper?

Now write some code to do the same thing!

Good luck!



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list