Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive function diag2list_rec ( grid ), where grid is an n × n square

ID: 3708111 • Letter: W

Question

Write a recursive function diag2list_rec(grid), where grid is an n× n square list of lists, that returns a list consisting of the diagonal elements of grid, i.e., the elements grid[0][0], grid[1][1], ..., grid[n–1][n–1].

You can assume that grid is a square list of lists, i.e., you don't have to check for this.

You must use a helper function useful for this problem.

Programming Requirements

Solve this problem using recursion. You are allowed to use onlythe following programming constructs:

if statements;

return statements;

assignment;

recursive function calls (if you use any helper functions then these must all be recursive as well);

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 diag2list_rec_helper(grid, i): if i == len(grid): # base case is when i is len(grid) return [] # return empty list else: return [grid[i][i]] + diag2list_rec_helper(grid, i + 1) # append diagonal element at row i column i to result to recursive call def diag2list_rec(grid): return diag2list_rec_helper(grid, 0)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote