Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly comment functions in Python

I would like advice on how I should structure my comments for functions. Is the description I currently have too in-depth?

The following code is for an algorithm that solves the n-queens problem.

def hill_climbing(initial_board):
    """
    While the current Board object has lower heuristic value successors, neighbour is randomly assigned to one.
    If the current Board's heuristic value is less than or equal to its neighbour's, the current Board object is
    returned. Else, the current variable is assigned the neighbour Board object and the while loop continues until
    either the current Board has no better successors, or current's h value is less than or equal to all of its
    successors.

    :param initial_board: A Board object with a randomly generated state, and successor_type of "best".
                          i.e. a start state
    :return: A Board object that has no further successors. i.e. a goal state (Local/Global Minimum)
    """
    current = initial_board
    while current.has_successors():
        neighbour = Board(current.get_random_successor(), "best")
        if neighbour.value() >= current.value():
            return current
        current = neighbour
    return current
like image 916
Joshua Avatar asked Mar 18 '26 02:03

Joshua


1 Answers

Thanks to Alexey's advice, I followed the PEPs and they provided great guidelines for commenting.

https://www.python.org/dev/peps/pep-0008/

https://www.python.org/dev/peps/pep-0257/

My resulting comment:

def hill_climbing(initial_board):
""" Hill Climbing Algorithm.

Performs a hill climbing search on initial_board and returns a Board
object representing a goal state (local/global minimum).

Attributes:
    current: A Board object
    neighbour: A Board object that is a successor of current

:param initial_board: A Board object with a randomly generated state, and successor_type of "best".
                      i.e. a start state
:return: A Board object that has no further successors. i.e. a goal state (Local/Global Minimum)
"""

current = initial_board
while current.has_successors():
    neighbour = Board(current.get_random_successor(), "best")
    if neighbour.value() >= current.value():
        return current
    current = neighbour
return current
like image 115
Joshua Avatar answered Mar 22 '26 12:03

Joshua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!