PROGRAMS
PROGRAMS
def print_board(board):
"""Prints the Tic-Tac-Toe board."""
for row in board:
print(" | ".join(row))
print("-" * 9)
# Check columns
for col in range(3):
if all(board[row][col] == player for row in range(3)):
return True
# Check diagonals
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
return True
return False
def is_draw(board):
"""Checks if the game is a draw."""
return all(board[row][col] != " " for row in range(3) for col in range(3))
def tic_tac_toe():
"""Main function to run the Tic-Tac-Toe game."""
board = [[" " for _ in range(3)] for _ in range(3)]
players = ["X", "O"]
turn = 0
print("Welcome to Tic-Tac-Toe!")
print_board(board)
while True:
player = players[turn % 2]
print(f"Player {player}, it's your turn.")
while True:
try:
row, col = map(int, input("Enter row and column (0-2, separated by space): ").split())
if board[row][col] == " ":
board[row][col] = player
break
else:
print("That spot is already taken. Try again.")
except (ValueError, IndexError):
print("Invalid input. Enter row and column numbers between 0 and 2.")
print_board(board)
if check_winner(board, player):
print(f"🎉 Player {player} wins!")
break
elif is_draw(board):
print("It's a draw!")
break
turn += 1
Output:
Welcome to Tic-Tac-Toe!
| |
---------
| |
---------
| |
Player X, it's your turn.
Enter row and column (0-2, separated by space): 0 0
X| |
---------
| |
---------
| |
Player O, it's your turn.
Enter row and column (0-2, separated by space): 1 1
X| |
---------
|O|
---------
| |
HILL CLIMBING
import random
def objective_function(x):
"""Function to maximize: f(x) = -x² + 4x"""
return -x**2 + 4*x # Example function
for _ in range(max_iterations):
# Generate possible next step
next_x = current_x + random.choice([-step_size, step_size])
next_value = objective_function(next_x)
OUTPUT