[SOLVED] How can I make my function return all the combinations of a grid horizontally?

Issue

So I wrote a function slanted(grid) which takes in a grid and returns the combination of letters horizontally.

For instance, if grid is

['q','q','d'],
['s','d','e'],
['e','g','h']

then slanted(grid) should return

['d','qe','qdh','sg','e']

I tried to do this by writing up this code for slanted(grid)

def slanted(grid):
    results = []
    for j in range(len(grid)-1):
        tmp = ""
        for i in range(len(grid)):
            tmp += [j+i][i]
            results.append(tmp)
    return results

print(slanted([['q','q','d'],['s','d','e'],['e','g','h']]))

but I’m getting an error message saying:

TypeError: can only concatenate str (not "int") to str

what changes to my code should I make to get the right output as indicated above?

Solution

[j + i][i] creates a singleton list with one integer, and then attempts to access that integer. You should try to access an element of grid, e.g. by doing grid[j + i][i], but this causes an IndexError.

Here is my approach to your task. You can think of this as reading a series of diagonals, each starting from a different start row / column index. For each start index, we extract that given diagonal:

def extract_diagonal(grid, start_row, start_col):
    row = start_row
    col = start_col
    letters = []

    while row < len(grid) and col < len(grid[0]):
        letters.append(grid[row][col])
        row += 1
        col += 1

    return ''.join(letters)

def slanted(grid):
    results = []
    for col in range(len(grid) - 1, -1, -1):
        results.append(extract_diagonal(grid, 0, col))

    for row in range(1, len(grid)):
        results.append(diagonal(grid, row, 0))

    return results

# Prints ['d','qe','qdh','sg','e'].
print(slanted([['q','q','d'],['s','d','e'],['e','g','h']]))

Note that we’re using ''.join() rather than repeated string concatenation here, as the former has a better time complexity. For more discussion on this, see this answer.

Answered By – BrokenBenchmark

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.