Skip to the content.

Homeworks 3.10B

Popcorn Hack #1 Javascript: You can easily reverse an array using the reverse() method. Here is an example using the numbers array from above.

Now create your own array and then reverse it using the reverse() method.

%%js
// Create an array with random elements
var randomArray = ["apple", "banana", "cherry", "date", "elderberry"];

// Reverse the array
randomArray.reverse();

// Print the reversed array
console.log(randomArray); // Output: ["elderberry", "date", "cherry", "banana", "apple"]

<IPython.core.display.Javascript object>

Popcorn Hack #2 Javascript: You can combine the push() with the spread operator (…) to add multiple items to an array at once. This also works with the unshift() method. For example:

Make your own array using the unshift() method and the spread operator.

%%js 
// Create an initial array
var fruits = ["banana", "orange", "apple"];

// New array to add
var moreFruits = ["grape", "strawberry"];

// Use unshift with the spread operator to add moreFruits to the beginning
fruits.unshift(...moreFruits);

// Print the updated array
console.log(fruits); // Output: ["grape", "strawberry", "banana", "orange", "apple"]

<IPython.core.display.Javascript object>

Popcorn Hack #3 Javascript: Instead of manually iterating through an array and counting every “long name,” you can use the filter() method. For example:

Make your own array using the filter() method

%%js
// Create an array of colors
var colors = ['Red', 'Blue', 'Yellow', 'Purple', 'Green', 'Orange'];

// Use filter() to find colors with more than 5 letters
var longColorCount = colors.filter(color => color.length > 5).length;

// Print the count of colors with more than 5 letters
console.log(longColorCount); // Output: 3

<IPython.core.display.Javascript object>

Popcorn Hack #1 Python: We can use the insert() method to add values at a certain index. Negative indexes count from the end of the list.

Make your own list (with numbers or strings), and add values to it using the insert() method with negative indexes

# Create a list of cities
cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

# Use insert() with negative indexes to add values at specific positions
cities.insert(-1, "Miami")       # Adds "Miami" at the second-to-last position
cities.insert(-3, "San Francisco")  # Adds "San Francisco" three places from the end

# Print the updated list
print(cities)

['New York', 'Los Angeles', 'Chicago', 'San Francisco', 'Houston', 'Miami', 'Phoenix']

Popcorn Hack #2 Python: We can use the extend() method to add two lists together.

Make two lists and add them together using the extend() popcorn hack.

# Create two lists of animals
animals = ["dog", "cat", "rabbit"]
more_animals = ["lion", "tiger", "elephant"]

# Using extend() to add more_animals to animals
animals.extend(more_animals)

# Print the combined list
print(animals)

['dog', 'cat', 'rabbit', 'lion', 'tiger', 'elephant']

Popcorn Hack #3 Python: You can also remove items by using the del (short for delete) function.

Create your own list, and remove three items from the list using three different methods.

# Create a list of colors
colors = ["red", "blue", "green", "yellow", "purple", "orange"]

# Method 1: Using del to remove the item at index 2
del colors[2]  # Removes "green"

# Method 2: Using remove() to remove an item by value
colors.remove("yellow")  # Removes "yellow"

# Method 3: Using pop() to remove the last item or by index
colors.pop()  # Removes the last item, "orange"

# Print the updated list
print(colors)

['red', 'blue', 'purple']

Python Homework Hack #1: Problem #1 - Objective: Create a simple program to manage a grocery list.

# Step 1: Create an empty list to store grocery items
grocery_list = []

# Step 2: Pre-fill the list with three grocery items
grocery_list = ["milk", "eggs", "bread"]

# Step 3: Display the current grocery list
print("\nCurrent grocery list:", grocery_list)

# Step 4: Sort the list alphabetically and print the sorted list
grocery_list.sort()
print("\nSorted grocery list:", grocery_list)

# Step 5: Remove one item specified by the user
item_to_remove = input("\nEnter the item you want to remove: ")
if item_to_remove in grocery_list:
    grocery_list.remove(item_to_remove)
    print("\nUpdated grocery list:", grocery_list)
else:
    print(f"{item_to_remove} is not in the grocery list.")

Current grocery list: ['milk', 'eggs', 'bread']

Sorted grocery list: ['bread', 'eggs', 'milk']

Updated grocery list: ['bread', 'eggs']

Python Homework Hack #2: Problem #2 - Filtering Even Numbers Objective: Create a list of numbers and filter for even numbers.

Print the list of even numbers.

# Step 1: Create a list of integers from 1 to 20
original_list = list(range(1, 21))

# Step 2: Print the original list
print("Original list:", original_list)

# Step 3: Create a new list containing only the even numbers using list comprehension
even_numbers = [num for num in original_list if num % 2 == 0]

# Step 4: Print the list of even numbers
print("Even numbers:", even_numbers)

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Even numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Python Homework Hack#3- Problem #3 - Write a program that manages a list of student grades.

Create a new list that contains only grades above 60 and print this list.

# Step 1: Create an empty list to store student grades
grades = []

# Step 2: Input three grades (as integers) and add them to the list
grades.append(75)  # First grade
grades.append(50)  # Second grade
grades.append(85)  # Third grade

# Step 3: Print the list of grades after all grades are entered
print("List of grades:", grades)

# Step 4: Create a new list that contains only grades above 60
passing_grades = [grade for grade in grades if grade > 60]

# Step 5: Print the list of passing grades
print("Grades above 60:", passing_grades)

List of grades: [75, 50, 85]
Grades above 60: [75, 85]

Python Homework Hack #4- Problem #4 Problem #4 - Number List Operations Objective: Create a list of numbers and perform basic operations.

Sort the list again at the end in ascending order and print it.

# Step 1: Create a list of numbers from 1 to 10 (integers)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Step 2: Print the original list
print("Original list:", numbers)

# Step 3: Sort the list in descending order
numbers.sort(reverse=True)
print("Sorted in descending order:", numbers)

# Step 4: Slice the list to get the first five numbers and print them
first_five = numbers[:5]
print("First five numbers:", first_five)

# Step 5: Sort the list again in ascending order and print it
numbers.sort()
print("Sorted in ascending order:", numbers)

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sorted in descending order: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
First five numbers: [10, 9, 8, 7, 6]
Sorted in ascending order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Javascript Homework Hack 1: Problem 1

%%js 
// Step 1: Create an array with at least 5 values
var myArray = [5, 10, 15, 20, 25];

// Step 2: Display the array
console.log("Original array:", myArray);

// Bonus: Reverse the array using the reverse() method
myArray.reverse();

// Display the reversed array
console.log("Reversed array:", myArray);

<IPython.core.display.Javascript object>

Javascript Hack 2: Problem 2

%%js 
// Given array of sports
var sports = ["soccer", "football", "basketball", "wrestling", "swimming"];

// Accessing elements using their indexes
var firstSport = sports[0];    // "soccer" is at index 0
var fourthSport = sports[3];    // "wrestling" is at index 3

// Displaying the values
console.log(firstSport);   // Output: soccer
console.log(fourthSport);  // Output: wrestling

<IPython.core.display.Javascript object>

Javascript Hack 3: Problem 3

%%js
// Initialize the array with four items
var choresList = ["laundry", "dishes", "vacuuming", "dusting"];

// Display the initial chores list
console.log("Initial chores list:", choresList);

// Use push() to add an item to the end
choresList.push("mopping");
console.log("After push (mopping):", choresList);

// Use unshift() to add an item to the beginning
choresList.unshift("grocery shopping");
console.log("After unshift (grocery shopping):", choresList);

// Use pop() to remove the last item
var removedItem = choresList.pop();
console.log("After pop (removed item: " + removedItem + "):", choresList);

// Use shift() to remove the first item
var shiftedItem = choresList.shift();
console.log("After shift (removed item: " + shiftedItem + "):", choresList);

// Bonus: Use push() and spread operator to add multiple values
var moreChores = ["cleaning windows", "organizing garage", "watering plants"];
choresList.push(...moreChores);
console.log("After pushing multiple items:", choresList);

<IPython.core.display.Javascript object>

Javascript Hack 4: Problem 4

%%js
// Create an array with ten random numbers (both even and odd)
var randomNumbers = [12, 7, 5, 4, 19, 22, 8, 15, 6, 3];

// Function to count even numbers
function countEvenNumbers(numbers) {
    let evenCount = 0; // Initialize count of even numbers

    // Iterate through the array
    for (var i = 0; i < numbers.length; i++) {
        // Check if the number is even
        if (numbers[i] % 2 === 0) {
            evenCount++; // Increment count if even
        }
    }

    return evenCount; // Return the count of even numbers
}

// Call the function and display the result
var count = countEvenNumbers(randomNumbers);
console.log("The count of even numbers in the array is:", count);

<IPython.core.display.Javascript object>