alphabeta

import math

def alphabeta(depth, nodeIndex, maximizingPlayer, values, alpha, beta):
# Base case: leaf node reached
if depth == 3:
return values[nodeIndex]

# Initialize bestEval based on whose turn it is
bestEval = -math.inf if maximizingPlayer else math.inf

# Loop through the two children (binary tree)
for i in range(2):
# Recursively call alphabeta. 'not maximizingPlayer' automatically toggles True to False, and False to True.
eval = alphabeta(depth + 1, nodeIndex * 2 + i, not maximizingPlayer, values, alpha, beta)

# Update the respective values based on the player
if maximizingPlayer:
bestEval = max(bestEval, eval)
alpha = max(alpha, eval)
else:
bestEval = min(bestEval, eval)
beta = min(beta, eval)

# Alpha-beta pruning condition
if beta <= alpha:
break

return bestEval

values = [3, 5, 6, 9, 1, 2, 0, -1]
result = alphabeta(0, 0, True, values, -math.inf, math.inf)
print("Optimal Value :", result)