Search code examples
pythondefinitionoptional-parametersargsoptional-arguments

How to enable an input of definition as optional?


I have a definition that iterates some functions. However, an argument or in other words input of this function should be optional. For my problem, I am trying to make 'depth' parameter optional. For example, this is a minimax algorithm but sometimes for the experiments, you might not want to apply depth pruning. Therefore, it should be optional.

I have tried the *args method. However, it did not work for me. Also, I made it 'depth = None' but I got an error due to 'depth - 1' value in dynamic programming.

def minimax(self, board_state, a, b, *args):
    for x in args:
        depth = x
    turn, board = board_state
    if super().terminal_state(board_state, depth):
        return super().heuristic_value(board_state)
    else:
        if turn == -1:
            value = 250
            for x in super().successor_generator(board_state):
                value = min(value, self.minimax(x, a, b, depth-1))
                b = min(b, value)
                if b <= a:
                    break
        elif turn == 1:
            value = -250
            for x in super().successor_generator(board_state):
                value = max(value, self.minimax(x, a, b, depth-1))
                a = max(a, value)
                if b <= a:
                    break

    result = board_state, value
    return value

object.minimax(state, a, b, depth=None)
value = min(value, self.minimax(x, a, b, depth-1))
TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'

The desired function should work for both way:

object.minimax(state, a, b) 
object.minimax(state, a, b, depth=5)

Solution

  • Your calls

    object.minimax(state, a, b) 
    object.minimax(state, a, b, depth=5)
    

    are correct and you should define your method as

    def minimax(self, board_state, a, b, depth=None)
    

    But after you have done that, what you should not do is

    value = min(value, self.minimax(x, a, b, depth-1))
    

    because you know that in some circumstances depth will be None and so depth-1 makes no sense in that case. You have to handle the exceptional None value explicitly yourself. One way to do that is

    value = min(value, self.minimax(x, a, b, depth-1 if depth is not None else None))