Skip to the content.

3.2_ipynb_2_

Popcorn hacks

#Popcorn hack 1
Dictionary = {"bananas": 1, "apples": 2, "pears": 3}
print(Dictionary["pears"]) #any key will do
%% js
// Popcorn hack 1
// Create an object to store the items and their values
const dictionary = {
    bananas: 1,
    apples: 2,
    pears: 3
};

// Access and print the value associated with the key "pears"
console.log(dictionary["pears"]); // Output: 3
#Popcorn hack 2
# Function to perform calculations
def calculator(num1, num2, operation):
    if operation in ['add', '+']:
        return num1 + num2
    elif operation in ['subtract', '-']:
        return num1 - num2
    elif operation in ['multiply', '*']:
        return num1 * num2
    elif operation in ['divide', '/']:
        if num2 == 0:
            return "Error: Division by zero is not allowed."
        return num1 / num2
    else:
        return "Error: Invalid operation."

# Get user input
first_input = input("Enter the first number: ")
num1 = float(first_input)

second_input = input("Enter the second number: ")
num2 = float(second_input)

operation = input("Enter the operation (add, subtract, multiply, divide): ")

# Calculate and print the result
result = calculator(num1, num2, operation)
print(f"Result: {result}")
%% js
// Popcorn hack 2
// Function to perform calculations
function calculator(num1, num2, operation) {
    switch (operation) {
        case 'add':
        case '+':
            return num1 + num2;
        case 'subtract':
        case '-':
            return num1 - num2;
        case 'multiply':
        case '*':
            return num1 * num2;
        case 'divide':
        case '/':
            if (num2 === 0) {
                return "Error: Division by zero is not allowed.";
            }
            return num1 / num2;
        default:
            return "Error: Invalid operation.";
    }
}

// Get user input from the command line
const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

readline.question('Enter the first number: ', (firstInput) => {
    const num1 = parseFloat(firstInput);

    readline.question('Enter the second number: ', (secondInput) => {
        const num2 = parseFloat(secondInput);

        readline.question('Enter the operation (add, subtract, multiply, divide): ', (operation) => {
            const result = calculator(num1, num2, operation);
            console.log(`Result: ${result}`);
            readline.close();
        });
    });
});
#Popcorn hack 3 
def repeat_strings(string_list, n):
    """
    Repeat each string in the list n times.

    Parameters:
    string_list (list): List of strings to be repeated.
    n (int): Number of times to repeat each string.

    Returns:
    list: A new list with each string repeated n times.
    """
    # Use a list comprehension to repeat each string n times
    return [s * n for s in string_list]

# Example usage
original_list = ["hello", "world", "python"]
n = 3
result = repeat_strings(original_list, n)
print(result)  # Output: ['hellohellohello', 'worldworldworld', 'pythonpythonpython']
%%js
// Popcorn hack 3
function repeatStrings(stringArray, n) {
    /**
     * Repeat each string in the array n times.
     *
     * @param {Array} stringArray - Array of strings to be repeated.
     * @param {number} n - Number of times to repeat each string.
     * @returns {Array} A new array with each string repeated n times.
     */
    return stringArray.map(s => s.repeat(n));
}

// Example usage
const originalArray = ["hello", "world", "javascript"];
const n = 2;
const result = repeatStrings(originalArray, n);
console.log(result);  // Output: ['hellohello', 'worldworld', 'javascriptjavascript']
%%js
// Popcorn hack 4
import java.util.HashSet;
import java.util.Set;

public class SetComparison {
    public static boolean compareSets(Set<Integer> set1, Set<Integer> set2) {
        // Check if any element in set2 exists in set1
        for (Integer element : set2) {
            if (set1.contains(element)) {
                return true; // Found a common element
            }
        }
        return false; // No common elements found
    }

    public static void main(String[] args) {
        Set<Integer> set1 = new HashSet<>();
        set1.add(1);
        set1.add(2);
        set1.add(3);
        set1.add(4);
        set1.add(5);

        Set<Integer> set2 = new HashSet<>();
        set2.add(5);
        set2.add(6);
        set2.add(7);
        set2.add(8);

        boolean result = compareSets(set1, set2);
        System.out.println(result); // Output: true
    }
}
#Popcorn hack 4
def compare_sets(set1, set2):
    """
    Compare two sets and check if there is any value in set2 that is in set1.

    Parameters:
    set1 (set): The first set to compare.
    set2 (set): The second set to compare.

    Returns:
    bool: True if there is a common element, False otherwise.
    """
    # Check for intersection between the two sets
    return not set1.isdisjoint(set2)

# Example usage
set1 = {1, 2, 3, 4, 5}
set2 = {5, 6, 7, 8}

result = compare_sets(set1, set2)
print(result)  # Output: True

Homework hack

# Part 1: Create Profile Information
profile = {
    "name": "John Doe",
    "age": 25,
    "city": "New York",
    "favorite_color": "Blue"
}

# Part 2: Create a List of Hobbies
hobbies = ["Reading", "Hiking", "Cooking"]
print("Hobbies:", hobbies)

# Part 3: Add Hobbies to Profile
profile["hobbies"] = hobbies
print("Updated Profile:", profile)

# Part 4: Check Availability of a Hobby
chosen_hobby = "Hiking"
has_hobby = chosen_hobby in hobbies
print(f"Is {chosen_hobby} available today? {has_hobby}")

# Part 5: Total Number of Hobbies
total_hobbies = len(hobbies)
print(f"I have {total_hobbies} hobbies.")

# Part 6: Favorite Hobbies
favorite_hobbies = ("Reading", "Hiking")
print("Favorite Hobbies:", favorite_hobbies)

# Part 7: Add a New Item to Your Profile (skills)
skills = {"Python", "Communication", "Problem Solving"}
print("Skills:", skills)

# Part 8: Decide to Add a New Skill
new_skill = None
print("New skill to learn:", new_skill)

# Part 9: Calculate Total Profile Cost
hobby_cost = 5
skill_cost = 10
total_cost = (total_hobbies * hobby_cost) + (len(skills) * skill_cost)
print("Total cost to develop hobbies and skills:", total_cost)
%%js
// Part 1: Create Profile Information
let profile = {
    name: "John Doe",
    age: 25,
    city: "New York",
    favorite_color: "Blue"
};

// Part 2: Create a List of Hobbies
let hobbies = ["Reading", "Hiking", "Cooking"];
console.log("Hobbies:", hobbies);

// Part 3: Add Hobbies to Profile
profile.hobbies = hobbies;
console.log("Updated Profile:", profile);

// Part 4: Check Availability of a Hobby
let chosenHobby = "Hiking";
let hasHobby = hobbies.includes(chosenHobby);
console.log(`Is ${chosenHobby} available today? ${hasHobby}`);

// Part 5: Total Number of Hobbies
let totalHobbies = hobbies.length;
console.log(`I have ${totalHobbies} hobbies.`);

// Part 6: Favorite Hobbies
let favoriteHobbies = ["Reading", "Hiking"];
console.log("Favorite Hobbies:", favoriteHobbies);

// Part 7: Add a New Item to Your Profile (skills)
let skills = new Set(["Python", "Communication", "Problem Solving"]);
console.log("Skills:", Array.from(skills));

// Part 8: Decide to Add a New Skill
let newSkill = null;
console.log("New skill to learn:", newSkill);

// Part 9: Calculate Total Profile Cost
let hobbyCost = 5;
let skillCost = 10;
let totalCost = (totalHobbies * hobbyCost) + (skills.size * skillCost);
console.log("Total cost to develop hobbies and skills:", totalCost);