3.3 Team lesson Popcorn Hacks + Homework

Popcorn hack are in both python first then javascript

Popcorn hack 1

def calculate_operations(a, b):
    """Performs basic arithmetic operations on two numbers and handles edge cases."""
    addition = a + b
    subtraction = a - b
    multiplication = a * b
    division = a / b if b != 0 else 'undefined'  # Handles division by zero
    modulus = a % b if b != 0 else 'undefined'
    exponentiation = a ** b  # Raises 'a' to the power of 'b'
    
    print(f"Add: {addition}")
    print(f"Subtract: {subtraction}")
    print(f"Multiply: {multiplication}")
    print(f"Divide: {division}")
    print(f"Modulus: {modulus}")
    print(f"Exponentiation: {exponentiation}")

def fibonacci(n):
    """Returns the nth Fibonacci number using an iterative approach for efficiency."""
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        a, b = 0, 1
        for i in range(2, n+1):
            a, b = b, a + b
        return b

# Example usage
a, b = 11, 3

# Perform operations
calculate_operations(a, b)

# Find the nth Fibonacci number (e.g., 7th Fibonacci number)
n = 7
print(f"The {n}th Fibonacci number is: {fibonacci(n)}")

Add: 14
Subtract: 8
Multiply: 33
Divide: 3.6666666666666665
Modulus: 2
Exponentiation: 1331
The 7th Fibonacci number is: 13
%%javascript
function calculateOperations(a, b) {
    // Perform basic arithmetic operations
    let addition = a + b;
    let subtraction = a - b;
    let multiplication = a * b;
    let division = b !== 0 ? a / b : 'undefined';  // Handles division by zero
    let modulus = b !== 0 ? a % b : 'undefined';
    let exponentiation = Math.pow(a, b);  // Raises 'a' to the power of 'b'
    
    console.log(`Add: ${addition}`);
    console.log(`Subtract: ${subtraction}`);
    console.log(`Multiply: ${multiplication}`);
    console.log(`Divide: ${division}`);
    console.log(`Modulus: ${modulus}`);
    console.log(`Exponentiation: ${exponentiation}`);
}

function fibonacci(n) {
    // Returns the nth Fibonacci number using an iterative approach
    if (n === 0) {
        return 0;
    } else if (n === 1) {
        return 1;
    } else {
        let a = 0, b = 1, temp;
        for (let i = 2; i <= n; i++) {
            temp = a + b;
            a = b;
            b = temp;
        }
        return b;
    }
}

let a = 11, b = 3;

calculateOperations(a, b);

let n = 7;
console.log(`The ${n}th Fibonacci number is: ${fibonacci(n)}`);

<IPython.core.display.Javascript object>

What I learned through this lesson + Hacks

  • Iterating through lists using loops.
  • Modifying lists: append, insert, remove.
  • Using conditional logic for dynamic data manipulation.
  • Index loops for element access and operations.
  • Simple input-output interaction for user-driven changes.
  • Arithmetic operations like summing even/odd numbers.
  • Error handling and input validation.
  • Encouraging simplicity and efficient coding.

Homework hacks

import logging
import sys

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(message)s')

def matrix_multiply(A, B):
    """
    Manually multiply two 2x2 matrices A and B.
    """
    return [
        [A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
        [A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]
    ]

def matrix_power(M, power):
    """
    Raise matrix M to the specified power using binary exponentiation.
    """
    result = [[1, 0], [0, 1]]  # Identity matrix
    while power > 0:
        if power % 2 == 1:
            result = matrix_multiply(result, M)
        M = matrix_multiply(M, M)
        power //= 2
    return result

def fibonacci_matrix(n):
    """
    Calculate the nth Fibonacci number using matrix exponentiation.
    """
    if n == 0:
        return 0
    elif n == 1:
        return 1

    F = [[1, 1], [1, 0]]  # The Fibonacci transformation matrix
    result = matrix_power(F, n - 1)
    
    return result[0][0]

def fibonacci_recursive(n):
    """
    Calculate the nth Fibonacci number using a recursive approach.
    """
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)

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 Fibonacci calculation using both matrix exponentiation and recursion.
    """
    try:
        user_input = input("Enter the position of the Fibonacci number you want to calculate: ")
        n = validate_input(user_input)
        
        fib_matrix = fibonacci_matrix(n)
        fib_recursive = fibonacci_recursive(n)
        
        print(f"Fibonacci number at position {n} (Matrix Exponentiation) is: {fib_matrix}")
        print(f"Fibonacci number at position {n} (Recursive) is: {fib_recursive}")
    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()

Fibonacci number at position 10 (Matrix Exponentiation) is: 55
Fibonacci number at position 10 (Recursive) is: 55

What I Learned About Fibonacci Sequences

  • The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding numbers.
  • It starts with 0 and 1, and follows the pattern: 0, 1, 1, 2, 3, 5, 8, 13....
  • The formula is: F(n) = F(n-1) + F(n-2), where F(n) represents the nth Fibonacci number.
  • The sequence is used to model growth patterns and solve algorithmic problems.
  • Fibonacci numbers appear in nature, such as in the arrangement of leaves, flowers, and even the branching of trees.

This sequecne can be useful for mathematical theory and practical applications like comp bio or computing and biology