Enhance readability of Minimax (#10838)

* Enhance readability of Minimax

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reduce line overflow

* Update backtracking/minimax.py

Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>

* Update backtracking/minimax.py

Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>

* Update backtracking/minimax.py

Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>

* Remove line overflow

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
This commit is contained in:
Hardik Pawar 2023-10-23 23:12:02 +05:30 committed by GitHub
parent 4cbefadbd7
commit 54e2aa67e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -16,6 +16,22 @@ def minimax(
depth: int, node_index: int, is_max: bool, scores: list[int], height: float
) -> int:
"""
This function implements the minimax algorithm, which helps achieve the optimal
score for a player in a two-player game by checking all possible moves.
If the player is the maximizer, then the score is maximized.
If the player is the minimizer, then the score is minimized.
Parameters:
- depth: Current depth in the game tree.
- node_index: Index of the current node in the scores list.
- is_max: A boolean indicating whether the current move
is for the maximizer (True) or minimizer (False).
- scores: A list containing the scores of the leaves of the game tree.
- height: The maximum height of the game tree.
Returns:
- An integer representing the optimal score for the current player.
>>> import math
>>> scores = [90, 23, 6, 33, 21, 65, 123, 34423]
>>> height = math.log(len(scores), 2)
@ -37,19 +53,24 @@ def minimax(
if depth < 0:
raise ValueError("Depth cannot be less than 0")
if len(scores) == 0:
raise ValueError("Scores cannot be empty")
# Base case: If the current depth equals the height of the tree,
# return the score of the current node.
if depth == height:
return scores[node_index]
# If it's the maximizer's turn, choose the maximum score
# between the two possible moves.
if is_max:
return max(
minimax(depth + 1, node_index * 2, False, scores, height),
minimax(depth + 1, node_index * 2 + 1, False, scores, height),
)
# If it's the minimizer's turn, choose the minimum score
# between the two possible moves.
return min(
minimax(depth + 1, node_index * 2, True, scores, height),
minimax(depth + 1, node_index * 2 + 1, True, scores, height),
@ -57,8 +78,11 @@ def minimax(
def main() -> None:
# Sample scores and height calculation
scores = [90, 23, 6, 33, 21, 65, 123, 34423]
height = math.log(len(scores), 2)
# Calculate and print the optimal value using the minimax algorithm
print("Optimal value : ", end="")
print(minimax(0, 0, True, scores, height))