3.2 Hacks
Python/Javascript Popcorn and HW hacks
Popcorn Hack #1
# Step 1: Create a Set
my_set = {1, 2, 3, 4, 5}
print("Initial set:", my_set)
# Step 2: Add an Element
my_set.add(6)
print("After adding 6:", my_set)
# Step 3: Remove an Element
my_set.remove(2)
print("After removing 2:", my_set)
# Step 4: Union of Sets
new_set = {7, 8, 9}
my_set = my_set.union(new_set)
print("After union with {7, 8, 9}:", my_set)
# Step 5: Clear the Set
my_set.clear()
print("After clearing the set:", my_set)
Popcorn Hack #2
# Step 1: Create a String
my_string = "Learning Python is not fun"
print("Original string:", my_string)
# Step 2: String Length
string_length = len(my_string)
print("Length of the string:", string_length)
# Step 3: String Slicing
extracted_word = my_string[9:15] # "Python" starts at index 9 and ends before index 15
print("Extracted word:", extracted_word)
# Step 4: String Uppercase
uppercase_string = my_string.upper()
print("Uppercase string:", uppercase_string)
# Step 5: String Replace
replaced_string = my_string.replace("fun", "good")
print("String after replacement:", replaced_string)
Original string: Learning Python is not fun
Length of the string: 26
Extracted word: Python
Uppercase string: LEARNING PYTHON IS NOT FUN
String after replacement: Learning Python is not good
Popcorn Hack #3
# Step 1: Create a List
my_list = [3, 5, 7, 9, 11]
print("Original list:", my_list)
# Step 2: Access an Element
third_element = my_list[2] # Index 2 corresponds to the third element
print("Third element:", third_element)
# Step 3: Modify an Element
my_list[1] = 6 # Change the second element (index 1) to 6
print("List after modifying second element:", my_list)
# Step 4: Add an Element
my_list.append(13) # Append 13 to the list
print("List after appending 13:", my_list)
# Step 5: Remove an Element
my_list.remove(9) # Remove the element 9 from the list
print("List after removing 9:", my_list)
# Bonus: Sort the list in descending order
my_list.sort(reverse=True)
print("Sorted list in descending order:", my_list)
Original list: [3, 5, 7, 9, 11]
Third element: 7
List after modifying second element: [3, 6, 7, 9, 11]
List after appending 13: [3, 6, 7, 9, 11, 13]
List after removing 9: [3, 6, 7, 11, 13]
Sorted list in descending order: [13, 11, 7, 6, 3]
Popcorn Hack #4 + Bonus
# Step 1: Create a Dictionary
personal_info = {
"name": "Vibha Jayanth Mandayam",
"email": "vibha@example.com",
"phone number": "123-456-7890"
}
# Step 2: Print out the Dictionary
print("Personal Info Dictionary:", personal_info)
# Step 3: Print out the name from your dictionary
print("My Name is:", personal_info["name"])
# Step 4: Print the Length
print("Overall Length of the Dictionary:", len(personal_info))
# Step 5: Print the Type
print("Overall Type of the Dictionary:", type(personal_info))
# Bonus: Add another dictionary with the same keys
another_person = {
"name": "Alex Smith",
"email": "alex@example.com",
"phone number": "098-765-4321"
}
# Print the new dictionary
print("Another Person's Info Dictionary:", another_person)
Personal Info Dictionary: {'name': 'Vibha Jayanth Mandayam', 'email': 'vibha@example.com', 'phone number': '123-456-7890'}
My Name is: Vibha Jayanth Mandayam
Overall Length of the Dictionary: 3
Overall Type of the Dictionary: <class 'dict'>
Another Person's Info Dictionary: {'name': 'Alex Smith', 'email': 'alex@example.com', 'phone number': '098-765-4321'}
Homework Hacks (Python)
Part 1: Create Personal Info (dict)
# Part 1: Create Personal Info (dict)
personal_info = {
"full_name": "Vibha Mandayam", # String
"years": 16, # Integer
"location": "San Diego", # String
"favorite_food": "Pizza" # String
}
# Print the dictionary to verify
print("Personal Info Dictionary:", personal_info)
Personal Info Dictionary: {'full_name': 'Vibha Mandayam', 'years': 16, 'location': 'San Diego', 'favorite_food': 'Pizza'}
Part 2: Create a List of Activities (list)
# Part 2: Create a List of Activities (list)
activities = [
"Reading",
"Coding",
"Playing basketball"
]
# Print the activities list
print("Activities List:", activities)
Part 3: Add Activities to Personal Info (dict and list)
# Part 1: Create Personal Info (dict)
personal_info = {
"full_name": "Vibha Mandayam",
"years": 16,
"location": "San Diego",
"favorite_food": "Pizza"
}
# Part 2: Create a List of Activities (list)
activities = [
"Reading",
"Coding",
"Playing basketball"
]
# Part 3: Add Activities to Personal Info (dict and list)
personal_info["activities"] = activities # Add the activities list to the dictionary
# Print the updated personal_info dictionary
print("Updated Personal Info Dictionary:", personal_info)
Updated Personal Info Dictionary: {'full_name': 'Vibha Mandayam', 'years': 16, 'location': 'San Diego', 'favorite_food': 'Pizza', 'activities': ['Reading', 'Coding', 'Playing basketball']}
Part 4: Check Availability of an Activity (bool)
# Part 1: Create Personal Info (dict)
personal_info = {
"full_name": "Vibha Mandayam",
"years": 15,
"location": "San Diego",
"favorite_food": "Pizza",
"activities": [
"Reading",
"Coding",
"Playing basketball"
]
}
# Part 4: Check Availability of an Activity (bool)
# Choose an activity to check
chosen_activity = "Coding"
# Set activity_available based on whether the activity is available today
activity_available = True # Set to False if the activity is not available today
# Print the availability message
print(f"Is '{chosen_activity}' available today? {activity_available}")
Is 'Coding' available today? True
Part 5: Total Number of Activities (int)
# Part 1: Create Personal Info (dict)
personal_info = {
"full_name": "Vibha Mandayam",
"years": 15,
"location": "SD",
"favorite_food": "Pizza",
"activities": [
"Reading",
"Coding",
"Playing basketball"
]
}
# Part 5: Total Number of Activities (int)
total_activities = len(personal_info["activities"]) # Get the number of activities in the list
# Print the message
print(f"I have {total_activities} activities.")
I have 3 activities.
Part 6: Favorite Activities (tuple)
# Part 6: Favorite Activities (tuple)
favorite_activities = (
"Reading",
"Coding"
)
# Print the favorite_activities tuple
print("Favorite Activities Tuple:", favorite_activities)
Part 7: Add a New Set of Skills (set)
# Part 7: Add a New Set of Skills (set)
skills = set() # Create an empty set
# Add unique skills to the set
skills.add("Python programming")
skills.add("Communication")
skills.add("Problem-solving")
# Print the set of skills
print("Skills Set:", skills)
Skills Set: {'Python programming', 'Problem-solving', 'Communication'}
Part 8: Consider a New Skill (NoneType)
# Part 8: Consider a New Skill (NoneType)
new_skill = None # You haven't decided yet
# Print the value of new_skill
print("New Skill:", new_skill)
New Skill: None
Part 9: Calculate Total Hobby and Skill Cost (float)
# Part 9: Calculate Total Hobby and Skill Cost (float)
# Define costs
activity_cost = 5.0 # Cost per activity
skill_cost = 10.0 # Cost per skill
# Number of activities and skills
total_activities = 3 # From previous steps
total_skills = len(skills) # Count the number of skills in the set
# Calculate total cost
total_cost = (total_activities * activity_cost) + (total_skills * skill_cost)
# Print the total cost
print(f"Total cost to pursue activities and develop skills: ${total_cost:.2f}")
Total cost to pursue activities and develop skills: $45.00
Javascript Popcorn Hacks
Popcorn Hack 1 (SETS):
// Create a set called Set1 of 3 numbers
const Set1 = new Set([1, 2, 3]); // You can choose any numbers
// Create a set called Set2 of different 3 numbers
const Set2 = new Set([4, 5, 6]); // Choose different numbers from Set1
// Log both sets separately
console.log("Set1:", Array.from(Set1));
console.log("Set2:", Array.from(Set2));
// Add a number to Set1
Set1.add(7); // Adding the number 7 to Set1
console.log("Set1 after adding 7:", Array.from(Set1));
// Remove the 1st number from Set1 (in this case, we remove the number 1)
Set1.delete(1); // Removing the number 1 from Set1
console.log("Set1 after removing 1:", Array.from(Set1));
// Log the union of both Set1 and Set2
const unionSet = new Set([...Set1, ...Set2]); // Create a union of both sets
console.log("Union of Set1 and Set2:", Array.from(unionSet));
// Create a Dictionary called "application"
const application = {
name: "Ruhee Banthia", // Name of the person
age: 15, // Age of the person
experiences: [ // Array of experiences
"Influencer",
"Veternarian",
"Swimmer"
],
money: 150000000 // Amount of money
};
// Log the dictionary to make sure it works
console.log("Application Dictionary:", application);
// Log only the dictionary’s money
console.log("Money:", application.money);
Homework Hacks
// Function to gather applicant information
function gatherApplicantInfo() {
// Create an empty dictionary (object) to store applicant information
const applicant = {};
// Ask for the applicant's name
applicant.name = prompt("What is your name?");
// Ask for the applicant's age
applicant.age = prompt("What is your age?");
// Ask for the applicant's experiences
const experiences = [];
let experience;
// Keep asking for experiences until the user types "done"
while (true) {
experience = prompt("Enter an experience (or type 'done' to finish):");
if (experience.toLowerCase() === 'done') {
break; // Exit the loop if the user types 'done'
}
experiences.push(experience); // Add the experience to the array
}
applicant.experiences = experiences; // Store the experiences in the dictionary
// Log the user's input
console.log("Applicant Information:", applicant);
}
// Call the function to gather information
gatherApplicantInfo();