Formatting the print path in a 2d grid

I have a 2d grid and a path through the grid, for example:

grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
path = [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)]

My desired result is a well-formatted output depicting a grid with the specified path:

  *1   2   3
  *4   5   6
  *7  *8  *9

Being new to Python, I don't quite understand how to use a list of concepts and formatting strings in it.

Here is what I still have:

def print_path(grid, path):
    print('\n'.join(''.join(['{:4}'.format(val) for val in row]) for row in grid))

--- Output ---

   1   2   3
   4   5   6
   7   8   9

My ideas for getting asterisks in front of specific path elements is to map the actual grid elements to the string representation that should be used as a result, like this:

1 => "*1"
2 => "2"
...
9 => "*9"

In general, the Python syntax feels overwhelming. I am trying to write more like Python-er, unlike Java-er (which I like). Any tips / hints / solutions would be greatly appreciated!

+4
3

, , .

In [36]: choose = {True: '*', False:''}
In [37]: print('\n'.join([' '.join(["{}{}".format(choose[(ind, i) in path], j) for i, j in enumerate(sub)]) for ind, sub in enumerate(grid)]))
*1  2  3
*4  5  6
*7 *8 *9


#Here is the broken version for more readability:

#'\n'.join([' '.join(
#          ["{}{}".format(choose[(ind, i) in path], j)
#           for i, j in enumerate(sub)])
#    for ind, sub in enumerate(grid)])
+3
def grid_counter(grid, path):
    for row, row_list in enumerate(grid):
        for column, column_num in enumerate(row_list):
            if (row, column) in path:
                print("*"+str(column_num), end=" ")
            else:
                print(str(column_num), end=" ")
        print("\n")

. comp.

0

and "unreadable" one insert

def print_path(grid, path):
    print('\n'.join(
            ''.join(['{:4}'.format('*' * ((i,j) in path) + str(val))
                     for j, val in enumerate(row)])
           for i, row in enumerate(grid)))

print_path(grid, path)
*1  2   3   
*4  5   6   
*7  *8  *9
0
source

Source: https://habr.com/ru/post/1671538/


All Articles