Skip to content

Commit 53c2a24

Browse files
Abdujabbarcclauss
andauthored
added type hints and doctests for minimax algorithm (#2478)
* added type hints and doctests for minimax algorithm * Update backtracking/minimax.py Co-authored-by: Christian Clauss <[email protected]> * last fix Co-authored-by: Christian Clauss <[email protected]>
1 parent daa1b4d commit 53c2a24

File tree

1 file changed

+48
-11
lines changed

1 file changed

+48
-11
lines changed

backtracking/minimax.py

+48-11
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import annotations
12
import math
23

34
""" Minimax helps to achieve maximum score in a game by checking all possible moves
@@ -9,26 +10,62 @@
910
"""
1011

1112

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+
"""
1338

14-
if Depth == height:
15-
return scores[nodeIndex]
39+
if depth < 0:
40+
raise ValueError("Depth cannot be less than 0")
1641

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:
1849
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),
2152
)
53+
2254
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),
2557
)
2658

2759

28-
if __name__ == "__main__":
29-
60+
def main():
3061
scores = [90, 23, 6, 33, 21, 65, 123, 34423]
3162
height = math.log(len(scores), 2)
32-
3363
print("Optimal value : ", end="")
3464
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

Comments
 (0)