0

2D List Mystery

Can someone please walk me through how to get these outputs for this 2D List Mystery code? I'm having trouble following it... def mystery(data, pos, n): result = set() for i in range(0, n): for j in range(0, n): result.add(data[i + pos][j + pos]) return result Suppose that a variable called grid has been declared as follows: grid = [[8, 2, 7, 8, 2, 1], [1, 5, 1, 7, 4, 7], [5, 9, 6, 7, 3, 2], [7, 8, 7, 7, 7, 9], [4, 2, 6, 9, 2, 3], [2, 2, 8, 1, 1, 3]] which means it will store the following 6-by-6 grid of values: 827821 151747 596732 787779 426923 228113 For each call below, indicate what value is returned. If the function call results in an error, write "error" instead. Function Call mystery(grid, 2, 2) mystery(grid, 0, 2) mystery(grid, 3, 3) Contents of Set Returned: {6, 7} {1, 2, 5, 8} {1, 2, 3, 7, 9}

9th May 2018, 8:53 PM
Taylor Deal
Taylor Deal - avatar
1 ответ
0
The position (pos) tells you where to start in that array, e.g. for 0 you start at data[0][0] = 8. Then n is the number of rows and columns you want to consider (thus a sub-square-matrix so to say). For n=2, range(0,n) means that i and j can have the values 0 and 1 (or in general from 0 to n-1). Note, that the result is a set, so only numbers that are not yet added to your set will be considered (as {1,2,2} is the same as {1,2}). Now again if you stride from position data[0][0], the inner loop goes through the columns first, i.e. data[0][0+0], data[0][1+0] For the given grid it is 8 and 2. Then i goes to next row (outer loop) data[1+0][0+0], data[1+0][1+0] which is 1 and 5. You add those numbers together in a set and thus {1,2,5,8}. For pos=2 and n=2, you consider the numbers 67 77 (figure out why, based on what I explained above) When added together in a set, it would be {6,7,7,7}, but this is the same as {6,7}, thus the given output.
19th May 2018, 12:08 PM
Matthias
Matthias - avatar