Team Teach 3.4 Homework and Popcorn Hacks
Showing how I was able to work and experiment with these.
3.4 Team lesson Popcorn Hacks + Homework
Popcorn hack are in both javascript then python
Popcorn hack 1
%%js
let favoriteMovie = "Alice in Wonderland";
let favoriteSport = "Football";
let petName = "Luna";
// Concatenation
let concatenatedMessage = "My favorite movie is " + favoriteMovie + ". I love playing " + favoriteSport + " and my pet's name is " + petName + ".";
// Interpolation
let interpolatedMessage = `My favorite movie is ${favoriteMovie}. I love playing ${favoriteSport} and my pet's name is ${petName}.`;
<IPython.core.display.Javascript object>
favorite_movie = "Alice in Wonderland"
favorite_sport = "Football"
pet_name = "Luna"
# Concatenation
concatenated_message = "My favorite movie is " + favorite_movie + ". I love playing " + favorite_sport + " and my pet's name is " + pet_name + "."
# Interpolation (using f-strings)
interpolated_message = f"My favorite movie is {favorite_movie}. I love playing {favorite_sport} and my pet's name is {pet_name}."
# Output the messages
print(concatenated_message)
print(interpolated_message)
My favorite movie is Ready Player One. I love playing Football and my pet's name is Luna.
My favorite movie is Ready Player One. I love playing Football and my pet's name is Luna.
Popcorn Hack 2
%%js
let phrase = "A journey of a thousand miles begins with a single step";
let partOne = phrase.slice(2, 8); // Extracts "journey"
let partTwo = phrase.slice(-18, -12); // Extracts "miles" using a negative starting index
let remainder = phrase.slice(20); // Extracts everything from "begins" to the end of the sentence
console.log("Extracted Word 1: " + partOne); // Output: journey
console.log("Extracted Word 2: " + partTwo); // Output: miles
console.log("Remainder of the Phrase: " + remainder); // Output: begins with a single step
<IPython.core.display.Javascript object>
phrase = "A journey of a thousand miles begins with a single step"
part_one = phrase[2:8]
part_two = phrase[-18:-12]
remainder = phrase[20:]
print("Extracted Word 1:", part_one)
print("Extracted Word 2:", part_two)
print("Remainder of the Phrase:", remainder)
Extracted Word 1: journe
Extracted Word 2: with a
Remainder of the Phrase: and miles begins with a single step
Popcorn hack 3 Removing Vowels
%%js
function removeVowels(inputStr) {
const vowels = "aeilouAEILOU";
let result = "";
for (let char of inputStr) {
if (!vowels.includes(char)) {
result += char;
}
}
return result;
}
const testSentence = "Coding is an adventure full of surprises!";
console.log(removeVowels(testSentence));
<IPython.core.display.Javascript object>
def remove_vowels(input_str):
vowels = "aeilouAEILOU" # Define vowels to remove
# Use list comprehension to filter out vowels
result = ''.join([char for char in input_str if char not in vowels])
return result
# Different sentence for testing
test_sentence = "Learning to code can be quite fun!"
# Call the function and print the result
print(remove_vowels(test_sentence))
rnng t cd cn b qt fn!
Reverse Order Popcorn Hack 4
%%js
function reverseWords(inputStr) {
const words = inputStr.split(" ");
const reversedWords = words.reverse().join(" ");
return reversedWords;
}
const sentence = "JavaScript is a versatile language!";
console.log(reverseWords(sentence));
<IPython.core.display.Javascript object>
def reverse_words(input_str):
words = input_str.split()
reversed_words = " ".join(reversed(words))
return reversed_words
sentence = "Learning Python is a rewarding experience!"
print(reverse_words(sentence))
experience! rewarding a is Python Learning
Overview of what I learned from the lesson
Popcorn Hack #1: Variable Definition and String Combination
Task: Define three variables for a movie, a sport, and a pet’s name, then combine them into a complete message using both concatenation and interpolation.
What I Learned: This hack taught me about string manipulation techniques and how to effectively combine strings in programming.
Popcorn Hack #2: String Slicing
Task: Use the slice() method to extract specific words from the string “A journey of a thousand miles begins with a single step.”
What I Learned: I learned how to manipulate strings with slicing, allowing for precise access to different parts of a string.
Popcorn Hack #3: Removing Vowels
Task: Create a function that removes all vowels from a given sentence, both uppercase and lowercase.
What I Learned: This hack enhanced my understanding of character filtering in strings using loops or list comprehensions.
Popcorn Hack #4: Reversing the Order of Words
Task: Reverse the order of words in a sentence without altering the characters within the words.
What I Learned: I learned about list and string manipulation by splitting, reversing, and joining elements, which is key for text data handling.
Homework Hack 1
%%js
function generateGreeting(firstName, lastName) {
if (!firstName || !lastName) {
throw new Error("Both first and last names are required!");
}
let concatenatedGreeting = "Hello, " + firstName + " " + lastName + "!";
let interpolatedGreeting = `Hello, ${firstName} ${lastName}!`;
return {
concatenated: concatenatedGreeting,
interpolated: interpolatedGreeting
};
}
function getUserInput() {
let firstName = prompt("Enter your first name:");
let lastName = prompt("Enter your last name:");
return { firstName, lastName };
}
function main() {
try {
const { firstName, lastName } = getUserInput();
const greetings = generateGreeting(firstName, lastName);
console.log(greetings.concatenated); // Output: Hello, John Doe!
console.log(greetings.interpolated); // Output: Hello, John Doe!
} catch (error) {
console.error(error.message);
}
}
main();
<IPython.core.display.Javascript object>
Greeting Message Explanation
Creating a greeting message like “Hello, [First Name] [Last Name]!” involves using string concatenation or interpolation to combine user input.
String Concatenation
String concatenation involves joining multiple strings using the + operator. For example:
let firstName = "John";
let lastName = "Doe";
let greeting = "Hello, " + firstName + " " + lastName + "!";
## Homework Hack 2
```python
import string
def is_palindrome(input_str):
# Normalize the string: convert to lowercase, remove spaces and punctuation
normalized_str = ''.join(char.lower() for char in input_str if char.isalnum())
# Check if the normalized string is equal to its reverse
return normalized_str == normalized_str[::-1]
def main():
user_input = input("Enter a string to check if it's a palindrome: ")
if is_palindrome(user_input):
print(f'"{user_input}" is a palindrome!')
else:
print(f'"{user_input}" is not a palindrome.')
# Execute the main function
if __name__ == "__main__":
main()
"1" is a palindrome!
Palindrome Explanation
A palindrome is a word, phrase, or sequence that reads the same forwards and backwards, like “level” or “A man, a plan, a canal, Panama!”
Palindrome Checker
A palindrome checker evaluates whether a string is a palindrome by:
- Normalizing the input (lowercasing and removing non-alphanumeric characters).
- Comparing the cleaned string with its reverse.
This simple tool helps in text analysis and ensures accurate data validation.