Question 42
Given a list L of integers, complete function abs_diff() using valid Python expressions/statements such that it returns a list of the absolute difference between every two consecutive integers in L.
Here is a sample run:
Note that your code needs to be syntactically correct to gain marks. You cannot use any semi-colon(;) and we will deduct marks if your answer is too long.
Model Solution
- Blank 1:
range(len(L)-1)- For a
range()function, if you use it in a for loop and specify a value like8for instance, we state that we want to iterate from0to7, which is before8. - In the next blank, we wish to refer to the value at index
i+1. Because of this, we want to avoid a case whereL[i+1]tries to get a value at a place that is considered out of bounds.
- For a
- Blank 2:
abs(L[i]-L[i+1])orabs(L[i+1]-L[i])- The
abs()function makes it so that you get the scalar difference and not a displacement value (i.e., not indicating whether it is a positive or negative difference).
- The
Another acceptable pair:
- Blank 1:
1, range(len(L)) - Blank 2:
abs(L[i-1]-L[i])orabs(L[i]-L[i-1])