Write a recursive function column2list_rec ( grid , n ), where grid is a list of
ID: 3708121 • Letter: W
Question
Write a recursive function column2list_rec(grid, n), where gridis a list of lists and n is an integer, that returns a list consisting of the element at position n of each row of grid.
You can assume that 0 ? n < len(r) for each row (i.e., element) of grid.
Programming Requirements
Solve this problem using recursion. You are allowed to use onlythe following programming constructs:
if statements;
return statements;
assignment;
recursive function calls (but not to helper functions);
comparison operations (==, !=, etc.);
list indexing and slicing;
list concatenation/extension.
Solutions that go outside these constructs, e.g., by using for/while loops or list comprehensions, will not get credit.
Explanation / Answer
# helper function def column2list_rec_helper(grid, n, i): if i == len(grid): # base case is when i is len(grid) return [] # return empty list else: return [grid[i][n]] + column2list_rec_helper(grid, n, i + 1) # append diagonal element at row i column i to result to recursive call def column2list_rec(grid, n): return column2list_rec_helper(grid, n, 0) print(column2list_rec([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 2))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.