Skip to the content.

3.3_teamteach_ipynb_2_

# Python Program to calculate total sum from 1 to n
n = int(input("Enter a number n: "))  # Prompt user for input
total_sum = 0  # Initialize total_sum to 0

# Loop to add numbers from 1 to n
for i in range(1, n + 1):
    total_sum += i  # Add each number to total_sum

# Print the total sum
print("Total sum from 1 to", n, "is:", total_sum)

Lesson 3.3.4 (Popcorn) - JavaScript

  • Hack: Create a function that uses 4 of the 5 basic arithmetic operations and returns the number 32
<script>
    // JavaScript function to return the number 32 using arithmetic operations
    function calculate() {
        let add = 10 + 10;       // Addition
        let subtract = add - 5;  // Subtraction
        let multiply = subtract * 4; // Multiplication
        let divide = multiply / 2; // Division
        return divide;  // Should return 32
    }
    
    // Call the function and log the result
    console.log("The result is:", calculate());
    element.append("The result is: " + calculate());
    </script>
    

3.3 Python Hacks!!!

Hack #1 (main) - python:

  • Define a List of Integers, Compute the Sum, and Print It
# Define a list of integers
integers = [3, 5, 7, 2, 8]

# Compute the sum of all integers
sum_of_integers = sum(integers)

# Print the sum
print(f"The sum of the integers is: {sum_of_integers}")

Hack #2 (main) - python:

  • Prompt User to Enter Price per Bag and Number of Bags, Calculate Total Cost
# Prompt user for price per bag and number of bags
price_per_bag = float(input("Enter the price per bag of popcorn: "))
num_bags = int(input("Enter the number of bags you want to buy: "))

# Calculate the total cost
total_cost = price_per_bag * num_bags

# Print the total cost
print(f"The total cost is: ${total_cost:.2f}")

Hack #3 (Main) - python:

  • Calculate Sum of Numbers from 1 to n
# Prompt the user to enter a number n
n = int(input("Enter a number: "))

# Initialize total_sum
total_sum = 0

# Use a loop to iterate from 1 to n
for i in range(1, n + 1):
    total_sum += i

# Print the total_sum
print(f"The sum of numbers from 1 to {n} is: {total_sum}")

Homework Hack #1 - python:

  • Compute Arithmetic Mean and Median
# Function to compute mean and median of a list of integers
def mean_and_median(integers):
    mean = sum(integers) / len(integers)
    sorted_integers = sorted(integers)
    
    # Compute median
    if len(sorted_integers) % 2 == 0:
        median = (sorted_integers[len(integers)//2 - 1] + sorted_integers[len(integers)//2]) / 2
    else:
        median = sorted_integers[len(integers)//2]
    
    # Print results
    print(f"Mean: {mean}")
    print(f"Median: {median}")

# Example usage
integers = [7, 2, 5, 9, 4]
mean_and_median(integers)

Homework Hack #2: Python

  • Collatz Sequence Function
# Function to generate the Collatz sequence
def collatz(a):
    sequence = [a]
    
    while a != 1:
        if a % 2 == 0:
            a = a // 2
        else:
            a = a * 3 + 1
        sequence.append(a)
    
    return sequence

# Example usage
a = int(input("Enter a positive integer: "))
collatz_sequence = collatz(a)
print(f"Collatz sequence starting at {a}: {collatz_sequence}")

3.3 Java Hacks!!

Popcorn Hack 1 Easy - Java

  • Create a function that uses 4 of the 5 basic arithmetic operations and returns the number 32 as the answer.
%% js 
function basicOperations() {
    let sum = 20 + 12;
    let difference = 40 - 8;
    let product = 8 * 4;
    let quotient = 64 / 2;

    // Since we need to return 32, we will use addition.
    return sum;
}

console.log(`The result is: ${basicOperations()}`);

Popcorn Hack 2: Medium Java

  • Make a function that lets you make a sandwich. Ask for different ingredients and at the end give the sandwich a name.
%%js
function makeSandwich() {
    let breadType = prompt("What type of bread do you want?");
    let mainIngredient = prompt("What is the main ingredient?");
    let condiment = prompt("What kind of condiment would you like?");
    let sandwichName = prompt("What would you like to name your sandwich?");

    let sandwich = `Your ${sandwichName} is made with ${breadType} bread, filled with ${mainIngredient}, and topped with ${condiment}.`;
    
    return sandwich;
}

console.log(makeSandwich());

Popcorn Hack 3: Hard Java

  • Create a “choose-your-own-path” type of game. There should be 2-3 different storylines the user can choose from.
%%js
function chooseYourPath() {
    let choice1 = prompt("You see a fight at school. Do you (a) break it up or (b) mind your own business?");

    if (choice1 === "a") {
        let choice2 = prompt("You decide to break it up. Do you (a) call a teacher or (b) jump in yourself?");
        if (choice2 === "a") {
            return "You call a teacher, and they resolve the situation. You're safe, but everyone thanks you!";
        } else if (choice2 === "b") {
            return "You jump into the fight and get hurt. Bad idea!";
        } else {
            return "Invalid choice!";
        }
    } else if (choice1 === "b") {
        let choice2 = prompt("You mind your own business. Do you (a) walk away or (b) watch from a distance?");
        if (choice2 === "a") {
            return "You walk away and avoid the chaos. Smart move!";
        } else if (choice2 === "b") {
            return "You watch from a distance and see a teacher arrive to break it up.";
        } else {
            return "Invalid choice!";
        }
    } else {
        return "Invalid choice!";
    }
}

console.log(chooseYourPath());

Homework Hack 1: (java) Compute GCD and LCM

  • Write a function that takes two variables and returns both the Greatest Common Divisor (GCD) and Least Common Multiple (LCM).
%%js
function gcdAndLcm(a, b) {
    // Helper function to compute the GCD
    function gcd(x, y) {
        while (y !== 0) {
            let temp = y;
            y = x % y;
            x = temp;
        }
        return x;
    }

    // Compute GCD
    let gcdResult = gcd(a, b);

    // Compute LCM
    let lcmResult = (a * b) / gcdResult;

    // Return the results as an object
    return { GCD: gcdResult, LCM: lcmResult };
}

console.log(gcdAndLcm(24, 36));

Homework Hack 2: (java) Prime Factors

  • Write a function that takes a positive integer and returns an array of its prime factors.
%%js 
function primeFactors(n) {
    let factors = [];
    
    // Start dividing by 2
    while (n % 2 === 0) {
        factors.push(2);
        n = n / 2;
    }

    // Try odd numbers from 3 onwards
    for (let i = 3; i <= Math.sqrt(n); i += 2) {
        while (n % i === 0) {
            factors.push(i);
            n = n / i;
        }
    }

    // If n is still a prime number greater than 2
    if (n > 2) {
        factors.push(n);
    }

    return factors;
}

console.log(`Prime factors of 84 are: ${primeFactors(84)}`);