|
| 1 | +from __future__ import annotations |
1 | 2 | import math
|
2 | 3 |
|
3 | 4 | """ Minimax helps to achieve maximum score in a game by checking all possible moves
|
|
9 | 10 | """
|
10 | 11 |
|
11 | 12 |
|
12 |
| -def minimax(Depth, nodeIndex, isMax, scores, height): |
| 13 | +def minimax(depth: int, node_index: int, is_max: bool, |
| 14 | + scores: list[int], height: float) -> int: |
| 15 | + """ |
| 16 | + >>> import math |
| 17 | + >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423] |
| 18 | + >>> height = math.log(len(scores), 2) |
| 19 | + >>> minimax(0, 0, True, scores, height) |
| 20 | + 65 |
| 21 | + >>> minimax(-1, 0, True, scores, height) |
| 22 | + Traceback (most recent call last): |
| 23 | + ... |
| 24 | + ValueError: Depth cannot be less than 0 |
| 25 | + >>> minimax(0, 0, True, [], 2) |
| 26 | + Traceback (most recent call last): |
| 27 | + ... |
| 28 | + ValueError: Scores cannot be empty |
| 29 | + >>> scores = [3, 5, 2, 9, 12, 5, 23, 23] |
| 30 | + >>> height = math.log(len(scores), 2) |
| 31 | + >>> minimax(0, 0, True, scores, height) |
| 32 | + 12 |
| 33 | + >>> minimax('1', 2, True, [], 2 ) |
| 34 | + Traceback (most recent call last): |
| 35 | + ... |
| 36 | + TypeError: '<' not supported between instances of 'str' and 'int' |
| 37 | + """ |
13 | 38 |
|
14 |
| - if Depth == height: |
15 |
| - return scores[nodeIndex] |
| 39 | + if depth < 0: |
| 40 | + raise ValueError("Depth cannot be less than 0") |
16 | 41 |
|
17 |
| - if isMax: |
| 42 | + if len(scores) == 0: |
| 43 | + raise ValueError("Scores cannot be empty") |
| 44 | + |
| 45 | + if depth == height: |
| 46 | + return scores[node_index] |
| 47 | + |
| 48 | + if is_max: |
18 | 49 | return max(
|
19 |
| - minimax(Depth + 1, nodeIndex * 2, False, scores, height), |
20 |
| - minimax(Depth + 1, nodeIndex * 2 + 1, False, scores, height), |
| 50 | + minimax(depth + 1, node_index * 2, False, scores, height), |
| 51 | + minimax(depth + 1, node_index * 2 + 1, False, scores, height), |
21 | 52 | )
|
| 53 | + |
22 | 54 | return min(
|
23 |
| - minimax(Depth + 1, nodeIndex * 2, True, scores, height), |
24 |
| - minimax(Depth + 1, nodeIndex * 2 + 1, True, scores, height), |
| 55 | + minimax(depth + 1, node_index * 2, True, scores, height), |
| 56 | + minimax(depth + 1, node_index * 2 + 1, True, scores, height), |
25 | 57 | )
|
26 | 58 |
|
27 | 59 |
|
28 |
| -if __name__ == "__main__": |
29 |
| - |
| 60 | +def main(): |
30 | 61 | scores = [90, 23, 6, 33, 21, 65, 123, 34423]
|
31 | 62 | height = math.log(len(scores), 2)
|
32 |
| - |
33 | 63 | print("Optimal value : ", end="")
|
34 | 64 | print(minimax(0, 0, True, scores, height))
|
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + import doctest |
| 69 | + |
| 70 | + doctest.testmod() |
| 71 | + main() |
0 commit comments