On Tue, 20 Sep 2016 09:52 pm, Daiyue Weng wrote:
> Hi, I have a list numbers say,
> 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])
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,
> and also put the rest numbers in another list, i.e. there is only one such
> list in the example,
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
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;
Hint: try keeping a list of lists. To start a new list, append an empty list
> Third, get the lists with the max/min sizes from above, i.e. in this
> example, the max list is,
> min list is
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!
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.