I made a function to see the movement of a two-dimensional array (Python)

Introduction

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 ↓ sample.gif

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.

Overwrite standard output

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='')

Align value lengths (display digits)

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)

Change the color of the string

\ 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'

in conclusion

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

I made a function to see the movement of a two-dimensional array (Python)
I made a function to check the model of DCGAN
I made a function to crop the image of python openCV, so please use it.
I made a program to check the size of a file in Python
Python: I want to measure the processing time of a function neatly
I made a script to record the active window using win32gui of Python
[Python3] Define a decorator to measure the execution time of a function
[Python] A simple function to find the center coordinates of a circle
Get the caller of a function in Python
Output in the form of a python array
I made a tool to estimate the execution time of cron (+ PyPI debut)
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
[python] How to sort by the Nth Mth element of a multidimensional array
I made an appdo command to execute a command in the context of the app
I want to see a list of WebDAV files in the Requests module
I made a tool to automatically back up the metadata of the Salesforce organization
[Python] I tried to get the type name as a string from the type function
I made a Python module to translate comment outs
Python Note: The mystery of assigning a variable to a variable
I tried to summarize the string operations of Python
I made a python text
[Python] I made an app to practice the subtle voice distinction of English words.
[Python / C] I made a device that wirelessly scrolls the screen of a PC remotely.
Try to get the function list of Python> os package
I just changed the sample source of Python a little.
I made a package to filter time series with python
I want to start a lot of processes from python
NikuGan ~ I want to see a lot of delicious meat! !!
I made a dot picture of the image of Irasutoya. (part1)
[Python] I tried to visualize the follow relationship of Twitter
I want to judge the authenticity of the elements of numpy array
I tried to implement the mail sending function in Python
I tried a little bit of the behavior of the zip function
I want to know the features of Python and pip
I tried to fight the Local Minimum of Goldstein-Price Function
A super introduction to Django by Python beginners! Part 6 I tried to implement the login function
I made a Line-bot using Python!
I thought a little because the Trace Plot of the stan parameter is hard to see.
I made a tool to get the answer links of OpenAI Gym all at once
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
I made a class to get the analysis result by MeCab in ndarray with python
I made a fortune with Python.
[Python] Make the function a lambda function
I tried to create a Python script to get the value of a cell in Microsoft Excel
I also tried to imitate the function monad and State monad with a generator in Python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I made a daemon with Python
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
I want to get the name of the function / method being executed
I made a program to solve (hint) Saizeriya's spot the difference
I made a library to easily read config files with Python
How to determine the existence of a selenium element in Python
I tried to get the index of the list using the enumerate function
[Introduction to Python] How to split a character string with the split function
A story that struggled to handle the Python package of PocketSphinx
I created a Python library to call the LINE WORKS API
How to check the memory size of a variable in Python
[Introduction to Python] I compared the naming conventions of C # and Python.
I tried to make a regular expression of "time" using Python
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
I want to output the beginning of the next month with Python