Computer Science 2
*********
*********
Due Date: April 22, 2024
Python Program about a soccer tournaments
Purpose: We are going to create a Python program
that simulates a soccer tournament.
Complete the assignment below:
Let's create a Python program that simulates a soccer tournament with real professional teams. We'll use a simple elimination format for a 10-team tournament. This will involve generating random scores for matches and advancing the winner until a champion is declared.
Here's a more detailed explanation of the program structure:
List of Teams: We'll include 10 real professional soccer teams.
Tournament Setup: The teams will be randomly matched in the first round. Since we have 10 teams, 8 teams will compete in the first round, and 2 will receive a bye to the second round.
Match Simulation: Each match will have random scores generated for the two teams.
Advancement: Winners will advance to the next round. This will continue until the championship match.
Championship: The last two teams will compete for the title.
Result Output: The program will display the results of each match and ultimately the champion.
Here's the Python code to simulate this tournament:
You will need to create the following 3 files:
PX_Soccer_lastname.py (Actual python program)
PX_Soccer_lastname.png (Screen shot of program running in the IDE)
PX_Soccer_lastname.mp4 (Video)
(Explaining the program and running the program)
/* Instructions:
* Copy the python program code below.
*/
import random
def simulate_match(team1, team2):
score1 = random.randint(0, 5)
score2 = random.randint(0, 5)
result = f"{team1} {score1} - {score2} {team2}"
if score1 > score2:
winner = team1
elif score2 > score1:
winner = team2
else: # In case of a draw, we simulate extra time
winner = team1 if random.random() > 0.5 else team2
result += f" (Extra time win by {winner})"
return winner, result
def simulate_tournament(teams):
results = []
while len(teams) > 1:
next_round = []
random.shuffle(teams) # Shuffle teams for pairing
if len(teams) % 2 == 1:
next_round.append(teams.pop()) # Give bye to one team if odd number of teams
while teams:
team1 = teams.pop()
team2 = teams.pop()
winner, result = simulate_match(team1, team2)
next_round.append(winner)
results.append(result)
teams = next_round
return results, teams[0] # Return all match results and the champion
# List of teams
teams = [
"Manchester United", "Liverpool", "Barcelona",
"Real Madrid", "Bayern Munich", "Paris Saint-Germain",
"Juventus", "Chelsea", "Manchester City", "AC Milan"
]
results, champion = simulate_tournament(teams.copy())
print("\nTournament Results:")
for result in results:
print(result)
print("\nChampion:", champion)
How It Works:
simulate_match: Simulates a match between two teams and determines a winner.
In case of a draw, a random "extra time" winner is chosen.
simulate_tournament: Conducts all the rounds of the
tournament until a champion is determined.
Team list: You can modify this list to include any
set of professional teams you like.
This program gives a complete, albeit simple, soccer
tournament simulation. You can extend it by
incorporating specific game rules, a group stage, or player-specific stats.
*********
*********
Due date: April 26, 2024
Python Program about calculus
Purpose: We are going to create a Python program
that calculates derivatives and integrals.
Complete the assignment below:
A useful Python program related to calculus could be one that calculates derivatives and integrals using symbolic computation. We'll use the sympy library, which is great for symbolic mathematics in Python.
Here's a basic program that allows users to input a mathematical function, and then choose whether they want to compute the derivative or the integral of that function:
You will need to create the following 3 files:
PX_Calculus_lastname.py (Actual python program)
PX_Calculus_lastname.png (Screen shot of program running in the IDE)
PX_Calculus_lastname.mp4 (Video)
(Explaining the program and running the program)
/* Instructions:
* Copy the python program code below.
*/
import sympy as sp
def calculus_operations():
x = sp.symbols('x') # Define the variable
expr_input = input("Enter a function of x (e.g., x**2, sin(x), exp(x)): ")
expr = sp.sympify(expr_input) # Convert the input string into a symbolic expression
# Ask the user what they want to do with the function
operation = input("Type 'd' to differentiate, 'i' to integrate: ").strip().lower()
if operation == 'd':
# Differentiate the function
derivative = sp.diff(expr, x)
print("The derivative of", expr, "is:", derivative)
elif operation == 'i':
# Integrate the function
integral = sp.integrate(expr, x)
print("The integral of", expr, "is:", integral)
else:
print("Invalid operation. Please enter 'd' for differentiation or 'i' for integration.")
if __name__ == "__main__":
calculus_operations()
Be sure to install Sympy:
pip install sympy
*********
*********
Due date: April 30, 2024
Python Program about Tic Tac Toe
Purpose: We are going to create a Python program
to play tic tac toe.
Complete the assignment below:
You will need to create the following 3 files:
PX_TicTacToe_lastname.py (Actual python program)
PX_TicTacToe_lastname.png (Screen shot of program running in the IDE)
PX_TicTacToe_lastname.mp4 (Video)
(Explaining the program and running the program)
/* Instructions:
* Copy the python program code below.
*/
Python program for a two-player Tic-Tac-Toe game.
It uses the console for input and output,
letting two players take turns to
mark Xs and Os on a 3x3 grid.
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board, player):
# Check rows, columns, and diagonals for a win
win_conditions = [
[board[0][0], board[0][1], board[0][2]],
[board[1][0], board[1][1], board[1][2]],
[board[2][0], board[2][1], board[2][2]],
[board[0][0], board[1][0], board[2][0]],
[board[0][1], board[1][1], board[2][1]],
[board[0][2], board[1][2], board[2][2]],
[board[0][0], board[1][1], board[2][2]],
[board[2][0], board[1][1], board[0][2]]
]
if [player, player, player] in win_conditions:
return True
return False
def tic_tac_toe():
board = [[" " for _ in range(3)] for _ in range(3)]
player_turn = "X"
moves_count = 0
while True:
print(f"Player {player_turn}'s turn.")
print_board(board)
try:
row = int(input("Enter the row number (1-3): ")) - 1
col = int(input("Enter the column number (1-3): ")) - 1
if board[row][col] == " ":
board[row][col] = player_turn
moves_count += 1
else:
print("This cell is already taken. Try another one.")
continue
except (ValueError, IndexError):
print("Invalid input. Please enter numbers between 1 and 3.")
continue
if check_winner(board, player_turn):
print_board(board)
print(f"Player {player_turn} wins!")
break
elif moves_count == 9:
print_board(board)
print("It's a draw!")
break
player_turn = "O" if player_turn == "X" else "X"
if __name__ == "__main__":
tic_tac_toe()
How to Use This Program:
Start the Game: Run the script in your Python environment. The game starts automatically.
Player Turns: The program asks each player (X and O) to enter the row and column where they want to place their mark. Rows and columns are numbered from 1 to 3.
End of Game: The game ends when one player has three of their marks in a row (horizontally, vertically, or diagonally) or when all nine squares are filled, resulting in a draw.
Players need to enter row and column numbers each turn, and the board is updated and displayed after each move. The game detects and announces a winner or a draw and then terminates.
*********
*********
*********
Resources you may need and select Web addresses you may need (Below)
*********
*********
*********
*********
*********