I think there are times when you want to observe changes in a two-dimensional array, mainly in competition professionals. DP or DP.
If it is a one-dimensional array, it is quite difficult to see if you print the two-dimensional array sequentially.
So, I prepared a function to watch the change of the 2D array.
Click here for the finished product ↓
from time import sleep
def print_2d_overwrite(list2d, val_width=5, sleep_sec=1.0, header=None, highlights=[]):
res_str = f'{header}\n' if header is not None else ''
for i, row in enumerate(list2d):
for j, v in enumerate(row):
v_str = str(v).rjust(val_width)
if (i,j) in highlights:
v_str = f'\033[31m{v_str}\033[0m'
res_str += f' {v_str}'
res_str += '\n'
new_line_cnt = res_str.count('\n')
res_str += f'\033[{new_line_cnt}A'
print(res_str, end='')
sleep(sleep_sec)
# --- sample ---
n = 3
list2d = [ [0]*n for _ in range(n)]
for i in range(n):
for j in range(n):
list2d[i][j] = 3**(i+j)
print_2d_overwrite(list2d, val_width=3, header=(i,j), highlights=[(i,j)])
The state of operation is ↓

The points are as follows.
--Overwrite standard output
--Align the lengths (display digits) of the values
--Change the color of the string
--sleep (just do time.sleep ())
(Added on 2020/11/19) In the comments, I received a technical writing style.
Related article was posted yesterday and I was surprised. The article I referred to for implementation is here. These articles are enough to explain, so this time I will explain only the main points.
You can move the cursor up n lines with \ 033 [nA".
The 2D array you want to display is converted to the character string (res_str), the number of line breaks \ n in it is counted, and it is added at the end of the character string. It's easier to use the f string.
Don't forget end ='' in print.
new_line_cnt = res_str.count('\n')
res_str += f'\033[{new_line_cnt}A'
print(res_str, end='')
It's hard to see if the lengths are not the same like this
3 5 345
235 -48 123
1 2 3
So, I want to make the length (display digit) of each element the same.
3 5 345
235 -48 123
1 2 3
This time, we'll do this with str.rjust (n).
Align the character string to the right, and fill in the missing characters with the characters specified in the second argument (if nothing is specified, fill in spaces).
v_str = str(v).rjust(val_width)
\ 033 [31m The character string you want to change color \ 033 [0m is OK.
Color can be set from 30m to 37m. 31m is red.
(For details, click here](https://www.nomuramath.com/kv8wr0mp/))
In the function, I am changing the color of the value specified for highlights. This is also easy if you use the f character string.
if (i,j) in highlights:
v_str = f'\033[31m{v_str}\033[0m'
I've added it to the competition pro snippet as it may be useful for debugging.
I thought it would be more convenient to use the sleep part as a key input, but on a Mac, I couldn't use the keyboard without sudo, so it was troublesome, so leave it as it is.
Recommended Posts