![]() |
Home | Accounts | Setup | Verify | Play | Hacks |
3.3 Math Expressions all Hacks
all Hacks for Math Expressions
Popcorn Hack #1
A function that takes in 2 variables and adds, subtracts, multiplies, dividies, and mods the two numbers
def operations(a, b):
# Basic arithmetic operations with handling for division by zero
add = a + b
subtract = a - b
multiply = a * b
divide = a / b if b != 0 else 'undefined'
mod = a % b if b != 0 else 'undefined'
# Display the results
print(f"Add: {add}")
print(f"Subtract: {subtract}")
print(f"Multiply: {multiply}")
print(f"Divide: {divide}")
print(f"Mod: {mod}")
%%js
function operations(a, b) {
// Basic arithmetic operations with handling for division by zero
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = b !== 0 ? a / b : 'undefined';
const mod = b !== 0 ? a % b : 'undefined';
// Display the results
console.log(`Add: ${add}`);
console.log(`Subtract: ${subtract}`);
console.log(`Multiply: ${multiply}`);
console.log(`Divide: ${divide}`);
console.log(`Mod: ${mod}`);
}
<IPython.core.display.Javascript object>
Popcorn Hack #2
Use an algorithm to find certain values of the Fibonacci sequence. For example, your code should output the nth index in the sequence. An example of how the sequence works is 0,1,1,2,3,5,8,13. The pattern is you add the previous 2 numbers together to get the new number.
def fibonacc(n):
if n <= 0:
return "invalid"
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacc(n - 1) + fibonacc(n - 2)
n = 15
print(f"The {n}th Fibonacci number is: {fibonacc(n)}")
The 15th Fibonacci number is: 377
%%js
function fibonacci(n) {
// Find the nth Fibonacci number
if (n <= 0) return "Invalid input";
if (n === 1) return 0;
if (n === 2) return 1;
// Use a loop to find the nth Fibonacci number
let a = 0, b = 1;
for (let i = 2; i < n; i++) {
const temp = b;
b = a + b;
a = temp;
}
return b;
}
// Variables
const a = 11, b = 0;
const n = 10;
// Perform operations
operations(a, b);
// Print nth Fibonacci number
console.log(`The ${n}th Fibonacci number is: ${fibonacci(n)}`);
<IPython.core.display.Javascript object>
Homework Hack #1
import sys as np
import logging
import sys
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(message)s')
def matrix_multiply(A, B):
"""
Perform matrix multiplication between two numpy arrays A and B.
"""
logging.debug(f"Multiplying matrices:\n{A}\n{B}")
return np.dot(A, B)
def matrix_power(M, power):
"""
Raise matrix M to the specified power using binary exponentiation.
"""
if power < 0:
raise ValueError("Power must be a non-negative integer.")
result = np.identity(len(M), dtype=object) # Identity matrix
logging.debug(f"Initial identity matrix:\n{result}")
while power > 0:
if power % 2 == 1:
result = matrix_multiply(result, M)
logging.debug(f"Result after multiplying by M:\n{result}")
M = matrix_multiply(M, M)
logging.debug(f"Matrix M squared:\n{M}")
power //= 2
logging.debug(f"Power reduced to: {power}")
return result
def fibonacci_matrix(n):
"""
Calculate the nth Fibonacci number using matrix exponentiation.
"""
if not isinstance(n, int):
raise TypeError("Input must be an integer.")
if n < 0:
raise ValueError("Fibonacci number is not defined for negative integers.")
elif n == 0:
return 0
elif n == 1:
return 1
F = np.array([[1, 1],
[1, 0]], dtype=object)
result = matrix_power(F, n-1)
logging.info(f"Matrix raised to power {n-1}:\n{result}")
return result[0][0]
def validate_input(user_input):
"""
Validate the user input to ensure it's a non-negative integer.
"""
try:
value = int(user_input)
if value < 0:
raise ValueError
return value
except ValueError:
raise ValueError("Please enter a valid non-negative integer.")
def main():
"""
Main function to execute the Fibonacci calculation.
"""
try:
user_input = input("Enter the position of the Fibonacci number you want to calculate: ")
n = validate_input(user_input)
fib_n = fibonacci_matrix(n)
print(f"Fibonacci number at position {n} is: {fib_n}")
except ValueError as ve:
logging.error(ve)
except Exception as e:
logging.error(f"An unexpected error occurred: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
%%js
// Population growth using Dynamic Programming and Matrix Exponentiation
// Dynamic Programming approach to calculate the plant population growth
function calculatePopulationDP(n) {
// Base cases for initial population
if (n === 0) return 10; // Starting population of 10 plants
if (n === 1) return 20; // Population grows to 20 after 1 time period
// Variables to store the population of previous two time periods
let prev1 = 20, prev2 = 10;
let current = 0;
// Iteratively calculate population for time period n
for (let i = 2; i <= n; i++) {
current = prev1 + prev2; // Growth based on sum of previous two periods
prev2 = prev1;
prev1 = current;
}
return current;
}
// Matrix Exponentiation approach (O(log n)) to calculate population growth
function calculatePopulationMatrix(n) {
if (n === 0) return 10;
let growthMatrix = [
[1, 1],
[1, 0]
];
power(growthMatrix, n - 1);
// Result population is the top left element of the growthMatrix
return growthMatrix[0][0] * 20 + growthMatrix[0][1] * 10; // Initial populations in period 1 and 0
}
// Helper function to perform matrix exponentiation
function power(matrix, n) {
if (n === 0 || n === 1) return;
let multiplier = [
[1, 1],
[1, 0]
];
power(matrix, Math.floor(n / 2));
multiply(matrix, matrix); // Square the matrix
if (n % 2 !== 0) multiply(matrix, multiplier); // Multiply by multiplier if n is odd
}
// Matrix multiplication helper
function multiply(matrixA, matrixB) {
let x = matrixA[0][0] * matrixB[0][0] + matrixA[0][1] * matrixB[1][0];
let y = matrixA[0][0] * matrixB[0][1] + matrixA[0][1] * matrixB[1][1];
let z = matrixA[1][0] * matrixB[0][0] + matrixA[1][1] * matrixB[1][0];
let w = matrixA[1][0] * matrixB[0][1] + matrixA[1][1] * matrixB[1][1];
matrixA[0][0] = x;
matrixA[0][1] = y;
matrixA[1][0] = z;
matrixA[1][1] = w;
}
// Example usage
const n = 10;
console.log(`Population at time period ${n} using Dynamic Programming: ${calculatePopulationDP(n)}`);
console.log(`Population at time period ${n} using Matrix Exponentiation: ${calculatePopulationMatrix(n)}`);