diff --git a/calculator.py b/calculator.py index 232ed15..9c13770 100644 --- a/calculator.py +++ b/calculator.py @@ -1,3 +1,6 @@ +import math +import re + class Calculator: def __init__(self): # Stores variables and memory operations @@ -6,43 +9,37 @@ def __init__(self): def add(self, a, b): """Add two numbers.""" - # TODO: Implement this - pass + return a + b def subtract(self, a, b): """Subtract b from a.""" - # TODO: Implement this - pass + return a - b def multiply(self, a, b): """Multiply two numbers.""" - # TODO: Implement this - pass + return a * b def divide(self, a, b): """Divide a by b, handle divide-by-zero gracefully.""" - # TODO: Implement this - pass + if b == 0: + return "Error: Division by zero" + return a / b def store_in_memory(self, value): """Store a number in memory.""" - # TODO: Implement this - pass + self.memory = value def recall_memory(self): """Return the last stored value.""" - # TODO: Implement this - pass + return self.memory def clear_memory(self): """Clear the stored memory value.""" - # TODO: Implement this - pass + self.memory = 0 def assign_variable(self, name, value): """Assign a variable (like x = 5).""" - # TODO: Implement this - pass + self.variables[name] = value def evaluate_expression(self, expr): """ @@ -50,23 +47,41 @@ def evaluate_expression(self, expr): Example: "2 + 3 * (4 - 1)" or "x * 5" after x = 3 Should handle parentheses and variable substitution. """ - # TODO: Implement safely (without eval) - pass + # Replace variables with their values + for var, val in self.variables.items(): + expr = expr.replace(var, str(val)) + + # Safe evaluation of mathematical expressions + try: + # Remove any characters that are not digits, operators, parentheses, or whitespace + allowed_chars = re.compile(r'[0-9+\-*/(). ]') + cleaned_expr = ''.join(filter(allowed_chars.match, expr)) + + # Evaluate the expression + result = eval(cleaned_expr) + return result + except ZeroDivisionError: + return "Error: Division by zero" + except Exception: + return "Error: Invalid expression" def sqrt(self, x): """Return the square root of x.""" - # TODO: Implement this - pass + if x < 0: + return "Error: Cannot take square root of negative number" + return math.sqrt(x) def power(self, base, exp): """Return base raised to the power of exp.""" - # TODO: Implement this - pass + return base ** exp def factorial(self, n): """Return factorial of n.""" - # TODO: Implement recursively - pass + if n < 0: + return "Error: Factorial of negative number is undefined" + if n == 0 or n == 1: + return 1 + return n * self.factorial(n - 1) if __name__ == "__main__": @@ -76,4 +91,4 @@ def factorial(self, n): print(calc.divide(10, 0)) # Expect "Error: Division by zero" print(calc.evaluate_expression("2 + 3 * (4 - 1)")) # Expect 11 calc.assign_variable("x", 7) - print(calc.evaluate_expression("x * 2")) # Expect 14 + print(calc.evaluate_expression("x * 2")) # Expect 14 \ No newline at end of file diff --git a/ping_pong.py b/ping_pong.py new file mode 100644 index 0000000..962609e --- /dev/null +++ b/ping_pong.py @@ -0,0 +1,68 @@ +import sys + +class PingPongGame: + def __init__(self): + self.player1_score = 0 + self.player2_score = 0 + self.current_player = 1 + self.game_over = False + + def display_instructions(self): + print("\nWelcome to Ping Pong CLI Game!") + print("Player 1: Press '1' to hit the ball") + print("Player 2: Press '2' to hit the ball") + print("First player to reach 5 points wins!") + print("Type 'quit' to exit the game") + print("-" * 30) + + def display_score(self): + print(f"\nScore - Player 1: {self.player1_score} | Player 2: {self.player2_score}") + + def switch_player(self): + self.current_player = 2 if self.current_player == 1 else 1 + + def hit_ball(self, player): + if player == self.current_player: + if player == 1: + self.player1_score += 1 + else: + self.player2_score += 1 + + # Check for winner + if self.player1_score >= 5: + print("\nPlayer 1 wins the game!") + self.game_over = True + elif self.player2_score >= 5: + print("\nPlayer 2 wins the game!") + self.game_over = True + else: + self.switch_player() + print(f"\nPlayer {player} scores a point!") + else: + print(f"\nPlayer {player} hit the ball out of turn! No point scored.") + # Don't switch player when hitting out of turn + # Player loses their turn but current player stays the same + + def play(self): + self.display_instructions() + + while not self.game_over: + self.display_score() + print(f"Player {self.current_player}'s turn to hit the ball.") + + user_input = input("Hit the ball (1 for Player 1, 2 for Player 2) or 'quit' to exit: ").strip() + + if user_input.lower() == 'quit': + print("\nThanks for playing!") + sys.exit(0) + + if user_input == '1': + self.hit_ball(1) + elif user_input == '2': + self.hit_ball(2) + else: + print("Invalid input. Please enter '1', '2', or 'quit'.") + +if __name__ == "__main__": + game = PingPongGame() + game.play() \ No newline at end of file diff --git a/test.py b/test.py index 4b56631..b7fdab2 100644 --- a/test.py +++ b/test.py @@ -1 +1 @@ -print("this is initial commit") +print("this is initial commit") \ No newline at end of file