Skip to content

Question 46

Given a 2D "image" m, complete function double_image() with valid Python expressions/statements such that it scales the image by a factor of 2, so that every "pixel" in m becomes a 2x2 "larger pixel" in the output.

You are given a function czm(r,c) which is the same as create_zero_matrix(r,c) from lecture.

1
2
3
4
5
6
7
8
def double_image(m):
    r = len(m)
    c = len(m[0])
    output = _____1_____
    for i in range(_____2_____):
        for j in range(_____3_____):
            output[i][j] = _____4_____
    return output

Here is a sample run:

>>> m2 = [['.','#','.'],['#','#','#'],['.','#','.']]
>>> pprint(double_image(m2))
[['.', '.', '#', '#', '.', '.'],
 ['.', '.', '#', '#', '.', '.'],
 ['#', '#', '#', '#', '#', '#'],
 ['#', '#', '#', '#', '#', '#'],
 ['.', '.', '#', '#', '.', '.'],
 ['.', '.', '#', '#', '.', '.']]

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.

Hint (for czm(r, c))

You need not know how this function should look like. You only need to know that czm(r, c) will produce a matrix of dimensions \(r\times c\), where each of its cell values are 0.

def czm(r, c):
    return [([0]*c).copy() for _ in range(r)]
Model Solution
1
2
3
4
5
6
7
8
def double_image(m):
    r = len(m)
    c = len(m[0])
    output = czm(r*2,c*2)
    for i in range(r*2):
        for j in range(c*2):
            output[i][j] = m[i//2][j//2]
    return output
  • Blank 1: czm(r*2,c*2)
    • Setting the dimensions of the output: create a matrix of dimensions \((r\times 2)\times(c\times 2)\). For instance, the given image in the sample run has dimensions \(3\times 3\). Hence, double_image() needs to output a matrix of dimensions \(6\times 6\). Each of the zeros in this image matrix will be overridden later in the for loop coming after.
  • Blank 2: r*2
    • Also acceptable: len(output)
  • Blank 3: c*2
    • Also acceptable: len(output[0])
  • Blank 4: m[i//2][j//2]
    • Setting i//2 and j//2 as indexes to reference on the output matrix image allows each cell in the original matrix image to be repeated twice in each row and column before using the next cell.