The code should be viewable wihtout any confusion which leads to following rules for formatting:
-
Type declaration
If not clear, the declaration of variable types are needed.
i: int = None text: str = None lists: list = None list_in_list: list[list[]] = None anything: any = None any_class: Class = None
-
Comments
If you want to take notes on a class or function you can make use of VisualStudios comment features like the following
class Test(): ''' This is a `Test` class ''' def __init__(self, num: int, txt: str, yn: bool): ''' This is the initialization of the `Test` class Parameters: - num: int - txt: str - yn: bool '''
-
Unnesting
Nesting is describing the excessive use of indents which can be prevented. It mostly occures in multiple if-statements or for-loops
Unnesting with return
def return_smaller_int(first_num: int, second_num: int): if first_num < second_num: return first_num else: return second_num
This Code can easily be shortened in multiple ways. The first is intermediate but quite genius; The function will end as soon as a value is returned which leads to this solution:
def return_smaller_int(first_num: int, second_num: int): if first_num < second_num: return first_num return second_num
Although it seems a little cheesy, you can completely delete this function because it already exists! Here you could easily use the
max()ormin()function. And don't worry about your performance; Integrated functions are most likely faster because they're written in C. There are only a few exceptions.min(first_num, second_num)
More Unnesting Tips: Youtube: Why You Shouldn't Nest Your Code
-
Consistency
Don't use different names for the same variable in different functions and make a function describe itself:
def evaluate(state: GameState): return len(state.possible_moves) - len(state.other_possible_moves) def evaluate2(current_state: GameState): return len(current_state.opp_moves) - len(current_state.poss_moves)
You should rather do something like this:
def delta_current_possible_moves(state: GameState): return len(state.possible_moves) - len(state.other_possible_moves) def delta_other_possible_moves(state: GameState): return len(state.other_possible_moves) - len(state.possible_moves)

