3.3 HACKS
Student led teaching on Abstraction. Teaching how various data types can use abstraction for computational efficiency.
Popcorn Hack:
# Python Popcorn 1
# Hack #1
# Define a list of integers
numbers = [5, 10, 15, 20, 25]
# Compute the sum of all integers
total_sum = sum(numbers)
# Print the sum
print("The sum of all integers is:", total_sum)
The sum of all integers is: 75
Popcorn Hack 2:
# Hack #2
# Prompt the user to enter the price per bag of popcorn
price_per_bag = float(input("Enter the price per bag of popcorn: "))
# Prompt the user to enter the number of bags they want to buy
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 for {num_bags} bags of popcorn is: ${total_cost:.2f}")
The total cost for 2 bags of popcorn is: $20.00
Popcorn Hack 3:
# Hack #3
# Prompt the user to enter a number n
n = int(input("Enter a number n: "))
# Initialize total_sum to 0
total_sum = 0
# Use a loop to iterate from 1 to n and add each number to total_sum
for i in range(1, n+1):
total_sum += i
# Print the total_sum
print(f"The sum of all numbers from 1 to {n} is:", total_sum)
The sum of all numbers from 1 to 2 is: 3
PYTHON HACK:
# Staticstics make it easier to analyze data and find statistical values:
import statistics
# Function to compute the arithmetic mean and median
def compute_mean_median(numbers):
# Compute the arithmetic mean
mean = sum(numbers) / len(numbers)
# Compute the median using the statistics module
median = statistics.median(numbers)
# Print both results
print(f"Arithmetic mean: {mean}")
print(f"Median: {median}")
# Defined list of integers
numbers_list = [5, 12, 7, 9, 20, 11, 15, 13]
# Call the function
compute_mean_median(numbers_list)
Arithmetic mean: 11.5
Median: 11.5
# Function to generate the Collatz sequence
def collatz_sequence(a):
# Initialize an array to store the sequence
sequence = [a]
# Iterate until the number becomes 1
while a != 1:
if a % 2 == 0:
# If the number is even, divide by 2
a = a // 2
else:
# If the number is odd, multiply by 3 and add 1
a = 3 * a + 1
# Append the result to the sequence array
sequence.append(a)
# Print the sequence
print("Collatz sequence:", sequence)
# Call the function with a starting number
collatz_sequence(27)
Collatz sequence: [27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Popcorn Hack 1:
function arithmeticOperations() {
// Basic arithmetic operations: +, -, *, /
let result = (8 * 4) - 10 + (2 / 1); // This expression uses multiplication, subtraction, addition, and division
return result;
}
// Call the function
console.log("The result of the arithmetic operations is: " + arithmeticOperations());
Popcorn Hack 2:
function makeSandwich() {
console.log("Let's make a sandwich!");
// Asking for ingredients
let bread = prompt("What type of bread would you like?");
let meat = prompt("What type of meat would you like?");
let veggies = prompt("What type of vegetables would you like?");
let condiments = prompt("What condiments would you like?");
// Giving the sandwich a name
let sandwichName = prompt("Give your sandwich a name:");
// Printing the sandwich description
console.log(`You made a '${sandwichName}' sandwich with ${bread} bread, ${meat}, ${veggies}, and ${condiments}.`);
}
// Call the function
makeSandwich();
Popcorn Hack 3:
function chooseYourPath() {
console.log("Welcome to the Choose Your Own Path Game!");
// Introduction to the story
console.log("\nYou see a fight at school. Do you:");
console.log("1. Break it up");
console.log("2. Mind your own business");
// First choice
let choice1 = prompt("Choose 1 or 2:");
if (choice1 === "1") {
console.log("\nYou decide to break up the fight.");
console.log("The principal sees you and thanks you for intervening.");
console.log("You're now respected by your peers.");
// Second choice in the 'break it up' path
console.log("\nBut now the people who were fighting are mad at you. Do you:");
console.log("1. Apologize to them");
console.log("2. Ignore them and move on");
let choice2 = prompt("Choose 1 or 2:");
if (choice2 === "1") {
console.log("\nYou apologize and they forgive you. Peace is restored!");
} else {
console.log("\nYou ignore them, but they keep causing trouble. Eventually, you have to deal with them again.");
}
} else {
console.log("\nYou decide to mind your own business.");
console.log("The fight escalates, and the school gets involved. You feel guilty for not stepping in.");
// Second choice in the 'mind your own business' path
console.log("\nDo you:");
console.log("1. Talk to the principal about the incident");
console.log("2. Pretend like nothing happened");
let choice2 = prompt("Choose 1 or 2:");
if (choice2 === "1") {
console.log("\nThe principal appreciates your honesty, and you help prevent future fights.");
} else {
console.log("\nYou keep pretending, but eventually, rumors spread, and you feel worse about not helping.");
}
}
}
// Call the function
chooseYourPath();
Javascript Hack:
// Function to compute the GCD using the Euclidean algorithm
function gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
// Function to compute the LCM
function lcm(a, b) {
return (a * b) / gcd(a, b); // LCM is calculated by (a * b) / GCD
}
// Main function to return both GCD and LCM as an object
function computeGcdAndLcm(a, b) {
return {
gcd: gcd(a, b),
lcm: lcm(a, b)
};
}
// Test the function
let a = 12;
let b = 18;
let result = computeGcdAndLcm(a, b);
console.log(`GCD of ${a} and ${b} is: ${result.gcd}`);
console.log(`LCM of ${a} and ${b} is: ${result.lcm}`);
// Helper function to check if a number is prime
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
// Function to return an array of prime factors
function primeFactors(n) {
let factors = [];
let divisor = 2;
while (n >= 2) {
if (n % divisor === 0) {
factors.push(divisor);
n = n / divisor;
} else {
divisor++;
}
}
return factors;
}
// Main function to return prime factors or simply n if it's prime
function getPrimeFactors(n) {
if (isPrime(n)) {
return [n];
} else {
return primeFactors(n);
}
}
// Test the function
let n = 56;
console.log(`Prime factors of ${n} are: `, getPrimeFactors(n));
n = 17; // A prime number
console.log(`Prime factors of ${n} are: `, getPrimeFactors(n));