Skip to the content.

3.3 & 3.5 hacks

Lesson 3.3.1-4 popcorn hacks

#python popcorn hack (#3)

number = int(input())
total_sum = 0
for i in range (1, number +1):
        total_sum += i

print (total_sum)
21
%%js
//Javascript popcorn hack (easy)


function calculate() {
    return (2 * 3) ** 2 - 6 + 2 /1; //uses multiplication, exponents, subtraction, addition, and division
}

console.log(calculate()); // Output: 32
<IPython.core.display.Javascript object>

Lesson 3.3.3 python big hacks

#PYTHON HACK 1

#Define a list of integers
integers = [2, 8, 14, 21, 33]

#Function to calculate arithmetic mean
def calculate_mean(numbers):
    return sum(numbers) / len(numbers)

#Function to calculate median
def calculate_median(numbers):
    sorted_numbers = sorted(numbers)
    mid_index = len(sorted_numbers) // 2
    
    #use the middle element
    return sorted_numbers[mid_index]

#Calculate mean and median
mean = calculate_mean(integers)
median = calculate_median(integers)

#Print the results
print("Arithmetic Mean:", mean)
print("Median:", median)

Arithmetic Mean: 15.6
Median: 14
# PYTHON HACK 2

def collatz_sequence(a):
    sequence = [a]  #Initialize the list with the starting value 'a'
    
    #Continue until the value reaches 1
    while a != 1:  
        if a % 2 == 0:
            a = a // 2  #If even, divide by 2
        else:
            a = 3 * a + 1  #If odd, multiply by 3 and add 1
        sequence.append(a)  #Add the new value to the sequence
    
    #Print the resulting sequence
    print(sequence)

#plug in 7 to test
collatz_sequence(7) 
[7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]

Lesson 3.3.4 Javascript big hacks

%%js
//JAVASCRIPT HACK 1

//Function to find the GCD of two numbers
function findGCD(a, b) {
    while (b !== 0) {
        [a, b] = [b, a % b];  //Swap the values of a and b
    }
    return a;  //When b becomes 0, a is the GCD
}

//Function to find the LCM of two numbers
function findLCM(a, b) {
    return Math.abs(a * b) / findGCD(a, b); // a * b / GCD = LCM
}

//Function to return both GCD and LCM as an object
function gcdAndLcm(a, b) {
    const gcd = findGCD(a, b);  //Find GCD
    const lcm = findLCM(a, b);  //Find LCM
    return { GCD: gcd, LCM: lcm };  //Return both as an object
}

//Define a and b
let a = 1;
let b = 7;

//Call the function and print the result
console.log(gcdAndLcm(a, b)); //output {GCD: 1, LCM: 14}
<IPython.core.display.Javascript object>
%%js
//JAVASCRIPT HACK 2

function findPrimeFactors() {
    let n = 14;
    let primeFactors = [];
    
    // Check for number of 2s that divide n
    while (n % 2 === 0) {
        primeFactors.push(2); //use .push to add to array
        n = n / 2;
    }
    
    //now that n is odd
    for (let i = 3; i <= Math.sqrt(n); i += 2) {
        while (n % i === 0) {
            primeFactors.push(i); //use .push to add to array
            n = n / i;
        }
    }
    
    //check if n is a prime number > 2
    if (n > 2) {
        primeFactors.push(n);
    }

    return primeFactors;
}

console.log(findPrimeFactors()); // Output: [ 2, 7 ]

<IPython.core.display.Javascript object>

3.5.1-4 Popcorn Hacks

#POPCORN HACK 1
def check():
    number = float(input("Enter a number: ")) #prompt to enter number
    if number < 0:
        print("negitive number") #if < 0
    else:
        print ("non-negitive") #if > 0
check ()
non-negitive
#POPCORN HACK 2
def is_vowel(char): #char = charecter
    vowels = 'aeiou'
    if char.lower() in vowels:
        print(f"'{char}' is a vowel")
    else:
        print(f"'{char}' is not a vowel")

char = input("Enter a character: ")

if len(char) == 1:
    is_vowel(char)
else:
    print("Please enter a single character.")
'y' is not a vowel
%%js
//POPCORN HACK 3 (javascript hack)
function checkEvenOrOdd(number) {
    // determine if the number is even or odd
    if (number % 2 === 0) {
        console.log(number + " is even.");
    } else {
        console.log(number + " is odd.");
    }
}

// Example usage:
checkEvenOrOdd(4); // Plug in number to () ex: 4

<IPython.core.display.Javascript object>

3.5.3 Python big hacks

#PYTHON HACK 1
def generate_truth_table(variables, expression):

    # Number of rows is 2 to power of # of variables!
    num_rows = 2 ** len(variables)

    # Print header
    print(f"{' | '.join(variables)} | {expression}")
    print('-' * (len(variables) * 4 + len(expression) + 3))

    # Loop through each row (from 0 to 2^n - 1)
    for i in range(num_rows):
        # Generate binary values (0 or 1) for each variable
        values = [(i >> j) & 1 for j in range(len(variables) - 1, -1, -1)]

        # truth values
        truth_values = [bool(val) for val in values]

        # dictionary of variable values
        value_dict = dict(zip(variables, truth_values))

        # look at expression using the variable values
        result = eval(expression, {}, value_dict)

        # Print the rows of the truth table
        row = ' | '.join(str(value_dict[var]) for var in variables)
        print(f"{row} | {result}")

# tet variables
variables = ['A', 'B']
expression = '(A and B) or not A'
generate_truth_table(variables, expression)

A | B | (A and B) or not A
-----------------------------
False | False | True
False | True | True
True | False | False
True | True | True
#PYTHON HACK 2

# using De Morgan's Law to check answer
def check_answer(question, player_answer):
    if question == "Is 2 + 2 equal to 4?":
        # Correct answer yes
        return not (player_answer != "yes")  # Applying De Morgan's Law: not (A and B) is the same as (not A) or (not B)
    elif question == "Is the sky green?":
        # Correct answer no
        return not (player_answer != "no")  # Applying De Morgan's Law here to simplify logic
    elif question == "Is fire cold?":
        # Correct answer no
        return not (player_answer != "no")  # Another example of simplifying with De Morgan's Law
    else:
        # If the question is unknown, just return False
        return False

# List of questions
questions = [
    "Is 2 + 2 equal to 4?",
    "Is the sky green?",
    "Is fire cold?"
]

# Game logic
def game():
    print("Welcome to the De Morgan's Law Game!")
    score = 0
    total_questions = len(questions)

    # Ask each question
    for i in range(total_questions):
        question = random.choice(questions)
        print(f"Question {i+1}: {question}")
        player_answer = input("Answer (yes/no): ").lower()
        
        # Ensure valid input
        if player_answer not in ["yes", "no"]:
            print("Invalid answer! Please enter 'yes' or 'no'.")
            continue
        
        # Check the answer using De Morgan's Law logic
        if check_answer(question, player_answer):
            print("Correct!")
            score += 1
        else:
            print("Incorrect.")

    # End of the game
    print(f"Game over! Your score: {score}/{total_questions}")

# Start the game
if __name__ == "__main__":
    game()

Welcome to the De Morgan's Law Game!
Question 1: Is fire cold?
Correct!
Question 2: Is 2 + 2 equal to 4?
Incorrect.
Question 3: Is the sky green?
Correct!
Game over! Your score: 2/3

3.5.4 Javascript big hacks

%%js
//JAVASCRIPT HACK 1

function checkPassword(password) {
    // Check length
    if (password.length < 10) {
        return "Password must be at least 10 characters long.";
    }

    // Check uppercase letters
    if (!/[A-Z]/.test(password)) {
        return "Password must contain at least one uppercase letter.";
    }

    // Check lowercase letters
    if (!/[a-z]/.test(password)) {
        return "Password must contain at least one lowercase letter.";
    }

    // Check numbers
    if (!/[0-9]/.test(password)) {
        return "Password must contain at least one number.";
    }

    // Check spaces
    if (/\s/.test(password)) {
        return "Password cannot contain spaces.";
    }

    return "Password accepted!";
}

let password = "TestPassword1";  // put in password here to test

let result = checkPassword(password);
console.log(result);
<IPython.core.display.Javascript object>
%%js
//JAVASCRIPT HACK 2

function personalityQuiz() {
    let score = 0;

    // Array of 10 questions
    const questions = [
        "1. How do you prefer to spend your free time?\n1. Reading a book\n2. Hanging out with friends\n3. Exploring outdoors",
        "2. Which describes you best?\n1. Calm and thoughtful\n2. Social and outgoing\n3. Adventurous and active",
        "3. What is your favorite type of movie?\n1. Documentaries or dramas\n2. Comedies or romantic movies\n3. Action or adventure",
        "4. How do you handle stress?\n1. Stay calm and think it through\n2. Talk to friends\n3. Do something active to blow off steam",
        "5. What do you value most?\n1. Knowledge\n2. Relationships\n3. Freedom",
        "6. Which activity sounds the most fun to you?\n1. Solving a puzzle\n2. Attending a party\n3. Going hiking",
        "7. What is your ideal vacation?\n1. Visiting a museum or historical site\n2. Going on a group tour with friends\n3. An outdoor adventure like camping or climbing",
        "8. How do you make decisions?\n1. Carefully weigh all options\n2. Ask for advice from others\n3. Go with your gut instinct",
        "9. What motivates you?\n1. Learning something new\n2. Connecting with people\n3. Experiencing excitement",
        "10. How would your friends describe you?\n1. Thoughtful\n2. Fun-loving\n3. Adventurous"
    ];

    // Ask each question and update score
    for (let i = 0; i < questions.length; i++) {
        let answer = prompt(questions[i]);
        score += parseInt(answer); // Add the user's answer to the total score
    }

    // Personality result based on score
    if (score <= 15) {
        console.log("You are introspective and prefer quiet environments. You enjoy thinking deeply and spending time in calm, peaceful settings.");
    } else if (score <= 25) {
        console.log("You are social and enjoy spending time with others. You thrive in group settings and enjoy being around people.");
    } else {
        console.log("You are adventurous and always seeking excitement! You love trying new things and exploring the world around you.");
    }
}

personalityQuiz();
//when run it will promp you to awsner all the questions entering a number for your awsner
//it will add up all the scores to show your final score/personality
<IPython.core.display.Javascript object>