3.4 HACKS
Student led teaching on Abstraction. Teaching how various data types can use abstraction for computational efficiency.
Popcorn hack 1
# Sample lyrics of a clean song (made-up)
lyrics = """
In the morning light, I rise and shine
The world is bright, everything feels fine
In the morning light, I feel so free
I take a step, just me and the sea
The waves are calling, they dance and play
In the morning light, I greet the day
"""
# Title of the song
title = "In the morning light"
# 1. Count how many times the title appears in the lyrics
title_count = lyrics.count(title)
print(f"The title '{title}' appears {title_count} times in the lyrics.")
# 2. Find the index of the 50th word
words = lyrics.split()
if len(words) >= 50:
word_50_index = words[49] # Index is 0-based, so the 50th word is at index 49
print(f"The 50th word is '{word_50_index}' at index 49.")
else:
print("The lyrics do not contain 50 words.")
# 3. Replace the first verse with the last verse
# Split the lyrics into verses
verses = lyrics.strip().split("\n")
if len(verses) > 1:
verses[0], verses[-1] = verses[-1], verses[0] # Swap first and last verses
# Join the verses back into a single string
modified_lyrics = "\n".join(verses)
print("\nModified lyrics:\n", modified_lyrics)
# 4. Concatenate two verses together to make your own song
# For this example, we concatenate the first two verses
if len(verses) >= 2:
custom_song = verses[0] + "\n" + verses[1]
print("\nYour own custom song:\n", custom_song)
else:
print("Not enough verses to create a custom song.")
The title 'In the morning light' appears 3 times in the lyrics.
The lyrics do not contain 50 words.
Modified lyrics:
In the morning light, I greet the day
The world is bright, everything feels fine
In the morning light, I feel so free
I take a step, just me and the sea
The waves are calling, they dance and play
In the morning light, I rise and shine
Your own custom song:
In the morning light, I greet the day
The world is bright, everything feels fine
Popcorn hack 2
// Concatenate a flower with an animal to create a new creature
const flower = "Rose";
const animal = "Lion";
const newCreature = `${flower}${animal}`; // Using template literals
// Display the new creature
console.log("New Creature: " + newCreature); // Using regular quotes
console.log(`New Creature: ${newCreature}`); // Using template literals
// Define variables for the story
const creatureName = newCreature; // The name of the new creature
const description = "a majestic creature with the elegance of a flower and the strength of a lion.";
const dialogue = "I am the RoseLion, protector of the enchanted garden!";
// Create a short story about the creature
const story = `
Once upon a time in a magical forest, there lived a creature known as ${creatureName},
${description} One day, it said, '${dialogue}'
With its fierce roar and gentle petals, it brought peace to all the creatures in the forest.
People from far and wide would come to see the ${creatureName} and marvel at its beauty and power.
`;
// Display the story
console.log(story);
Python Hack
def text_analyzer():
# Accept input from the user
user_input = input("Enter a sentence or multiple words: ")
# Display the original string
print(f"\nOriginal string: {user_input}")
# Count total characters (including spaces)
total_characters = len(user_input)
print(f"Total characters (including spaces): {total_characters}")
# Find the longest word
words = user_input.split()
longest_word = max(words, key=len)
print(f"Longest word: '{longest_word}' with {len(longest_word)} characters.")
# Display the string reversed
reversed_string = user_input[::-1]
print(f"Reversed string: '{reversed_string}'")
# Find the middle word/character (excluding spaces)
cleaned_input = ''.join(user_input.split()) # Remove spaces
middle_index = len(cleaned_input) // 2
if len(cleaned_input) % 2 == 0:
middle_char = cleaned_input[middle_index-1:middle_index+1] # Even length
else:
middle_char = cleaned_input[middle_index] # Odd length
print(f"Middle character(s): '{middle_char}'")
# Custom function to replace words
word_to_replace = input("Enter a word to replace: ")
replacement_word = input("Enter the replacement word: ")
if word_to_replace in user_input:
modified_string = user_input.replace(word_to_replace, replacement_word)
print(f"Modified string: '{modified_string}'")
else:
print(f"The word '{word_to_replace}' was not found in the original string.")
# Run the analyzer
text_analyzer()
Original string: sentence
Total characters (including spaces): 8
Longest word: 'sentence' with 8 characters.
Reversed string: 'ecnetnes'
Middle character(s): 'te'
The word 'hello' was not found in the original string.
Javascript hack:
function textAnalyzer() {
// Accept input from the user
const userInput = prompt("Enter a sentence or multiple words:");
// Display the original string
console.log(`\nOriginal string: ${userInput}`);
// Count total characters (including spaces)
const totalCharacters = userInput.length;
console.log(`Total characters (including spaces): ${totalCharacters}`);
// Find the longest word
const words = userInput.split(" ");
const longestWord = words.reduce((a, b) => a.length >= b.length ? a : b);
console.log(`Longest word: '${longestWord}' with ${longestWord.length} characters.`);
// Display the string reversed
const reversedString = userInput.split("").reverse().join("");
console.log(`Reversed string: '${reversedString}'`);
// Find the middle word/character (excluding spaces)
const cleanedInput = userInput.replace(/\s+/g, ''); // Remove spaces
const middleIndex = Math.floor(cleanedInput.length / 2);
let middleChar;
if (cleanedInput.length % 2 === 0) {
middleChar = cleanedInput[middleIndex - 1] + cleanedInput[middleIndex]; // Even length
} else {
middleChar = cleanedInput[middleIndex]; // Odd length
}
console.log(`Middle character(s): '${middleChar}'`);
// Custom function to replace words
const wordToReplace = prompt("Enter a word to replace:");
const replacementWord = prompt("Enter the replacement word:");
if (userInput.includes(wordToReplace)) {
const modifiedString = userInput.replace(new RegExp(wordToReplace, 'g'), replacementWord);
console.log(`Modified string: '${modifiedString}'`);
} else {
console.log(`The word '${wordToReplace}' was not found in the original string.`);
}
}
// Run the analyzer
textAnalyzer();