The Nim code is a direct translation of the Python code - see the Python code for descriptive comments.