Skip to content

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.

1
2
3
4
5
def abs_diff(L):
    output = []
    for i in _____1_____:
        output.append(_____2_____)
    return output

Here is a sample run:

>>> print(abs_diff([1,2,4,9,3,1]))
[1, 2, 5, 6, 2]

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
1
2
3
4
5
def abs_diff(L):
    output = []
    for i in range(len(L)-1):
        output.append(abs(L[i]-L[i+1]))
    return output
  • Blank 1: range(len(L)-1)
    • For a range() function, if you use it in a for loop and specify a value like 8 for instance, we state that we want to iterate from 0 to 7, which is before 8.
    • In the next blank, we wish to refer to the value at index i+1. Because of this, we want to avoid a case where L[i+1] tries to get a value at a place that is considered out of bounds.
  • Blank 2: abs(L[i]-L[i+1]) or abs(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).

Another acceptable pair:

  • Blank 1: 1, range(len(L))
  • Blank 2: abs(L[i-1]-L[i]) or abs(L[i]-L[i-1])