Skip to the content.

3.10 Homework

3.10 Python Code

import time

# Function to add an element to the list
def add_element(my_list):
    element = input("šŸŽØ Enter an element to add: ")
    my_list.append(element)
    print(f"āœ… '{element}' has been added to the list!")

# Function to remove an element from the list
def remove_element(my_list):
    element = input("āŒ Enter an element to remove: ")
    if element in my_list:
        my_list.remove(element)
        print(f"šŸ—‘ļø '{element}' has been removed from the list!")
    else:
        print(f"āš ļø '{element}' is not in the list. Try again.")

# Function to check if an element exists in the list
def check_element(my_list):
    element = input("šŸ” Enter an element to check: ")
    if element in my_list:
        print(f"šŸ‘ '{element}' exists in the list!")
    else:
        print(f"šŸ‘Ž '{element}' is not in the list.")

# Function to display the current list
def display_list(my_list):
    if my_list:
        print("\nšŸ“œ Here is your current list:")
        for i, item in enumerate(my_list, 1):
            print(f"{i}. {item}")
    else:
        print("\nšŸ“œ Your list is currently empty.")

# Function to find the maximum and minimum value using iteration
def find_max_min(my_list):
    try:
        int_list = [int(i) for i in my_list]
    except ValueError:
        print("ā— List contains non-integer values. Please only use integers.")
        return

    max_value = int_list[0]
    min_value = int_list[0]
    
    for num in int_list:
        if num > max_value:
            max_value = num
        if num < min_value:
            min_value = num

    print(f"🌟 Maximum value: {max_value}")
    print(f"🌈 Minimum value: {min_value}")

# Main program loop
def main():
    my_list = []  # Initialize an empty list

    print("šŸŽ‰ Welcome to the Ultimate List Manager! šŸŽ‰")
    time.sleep(1)

    while True:
        print("\nChoose an option:")
        print("1. āž• Add an element")
        print("2. āž– Remove an element")
        print("3. šŸ”Ž Check if an element exists")
        print("4. šŸ“œ Display the current list")
        print("5. šŸ”¢ Find the maximum and minimum values in the list")
        print("6. 🚪 Exit")

        choice = input("Enter your choice: ")

        if choice == '1':
            add_element(my_list)
        elif choice == '2':
            remove_element(my_list)
        elif choice == '3':
            check_element(my_list)
        elif choice == '4':
            display_list(my_list)
        elif choice == '5':
            find_max_min(my_list)
        elif choice == '6':
            print("šŸ‘‹ Goodbye! Thanks for using the Ultimate List Manager!")
            break
        else:
            print("āš ļø Invalid choice, please try again.")

        time.sleep(0.5)  # Add a short delay for better user experience

# Run the main function
main()

3.10 JavaScript Code

%%js

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Shopping Cart Simulator šŸ›’</title>
</head>
<body>
  <h1>Welcome to the Shopping Cart Simulator! šŸ¬šŸ›’</h1>
  <p>Type in items to add or remove them from your shopping cart.</p>

  <!-- Buttons for adding and removing items -->
  <input type="text" id="itemInput" placeholder="Enter item name">
  <button onclick="addItem()">Add Item āž•</button>
  <button onclick="removeItem()">Remove Item āž–</button>

  <!-- Display the current cart -->
  <h2>Shopping Cart:</h2>
  <div id="cart"></div>

  <script>
    // Initialize an empty cart array
    let cart = [];

    // Function to add an item to the cart
    function addItem() {
      const itemInput = document.getElementById('itemInput');
      const item = itemInput.value.trim();
      
      if (item) {
        cart.push(item);
        alert(`šŸ›’ Added '${item}' to the cart!`);
        displayCart();
      } else {
        alert("Please enter an item name to add to the cart.");
      }

      itemInput.value = ''; // Clear the input field
    }

    // Function to remove an item from the cart
    function removeItem() {
      const itemInput = document.getElementById('itemInput');
      const item = itemInput.value.trim();
      
      if (item && cart.includes(item)) {
        cart = cart.filter(cartItem => cartItem !== item);
        alert(`āŒ Removed '${item}' from the cart.`);
        displayCart();
      } else if (item) {
        alert(`āš ļø '${item}' is not in the cart.`);
      } else {
        alert("Please enter an item name to remove from the cart.");
      }

      itemInput.value = ''; // Clear the input field
    }

    // Function to display the current cart
    function displayCart() {
      const cartDiv = document.getElementById('cart');
      cartDiv.innerHTML = ''; // Clear the cart display

      if (cart.length === 0) {
        cartDiv.innerHTML = "Your cart is empty.";
      } else {
        cartDiv.innerHTML = "Items in your cart:";
        cart.forEach((item, index) => {
          const itemElement = document.createElement('div');
          itemElement.innerHTML = `šŸ›ļø ${index + 1}. ${item}`;
          cartDiv.appendChild(itemElement);
        });
      }
    }

    // Initial cart display
    displayCart();
  </script>
</body>
</html>

Popcorn Hack 1

# Original list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("šŸŽ² Original list of numbers:", numbers)

# Using list comprehension to filter and transform the list
even_numbers = [num for num in numbers if num % 2 == 0]
odd_numbers = [num for num in numbers if num % 2 != 0]
squared_numbers = [num ** 2 for num in numbers]

# Displaying the results with some creative flair
print("\nšŸ”¹ Only the even numbers:")
for num in even_numbers:
    print(f"  - {num} is even")

print("\nšŸ”ø Only the odd numbers:")
for num in odd_numbers:
    print(f"  - {num} is odd")

print("\n✨ Squared values of all numbers:")
for original, squared in zip(numbers, squared_numbers):
    print(f"  - {original} squared is {squared}")

Popcorn Hack 2

// Part 1: Using reduce() to sum numbers
const numbers = [10, 20, 30, 40, 50];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log("Sum of numbers:", sum);

// Part 2: Sorting integers numerically
const randomIntegers = [9, 1, 77, 4, 80, 3, 8];
randomIntegers.sort((a, b) => a - b);
console.log("Sorted integers:", randomIntegers);

// Part 3: Sorting number words alphabetically
const numberWords = ["Nine", "One", "Seventy-Seven", "Four", "Eighty", "Three", "Eight"];
numberWords.sort();
console.log("Sorted number words:", numberWords);