Team Teach 3.1 Homework and Popcorn Hacks
Showing how I was able to work and experiment with these.
3.1 TEAM TEACH (Monday)
Popcorn Hack 1
import random
import time
def play_game():
score = 0
operators = ['+', '-', '*', '/']
time_limit = 10 # Player has 10 seconds to answer
print("Welcome to the Math Quiz Game!")
print(f"Answer as many questions as you can within {time_limit} seconds for each question. Type 'q' to quit anytime.\n")
while True:
# Generate two random numbers and choose a random operator
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
op = random.choice(operators)
# Ensure the division results in a whole number
if op == '/':
num1 = num1 * num2 # Makes sure num1 is divisible by num2
# Calculate the correct answer based on the operator
if op == '+':
answer = num1 + num2
elif op == '-':
answer = num1 - num2
elif op == '*':
answer = num1 * num2
else: # Division case
answer = num1 // num2 # Integer division for whole number results
# Ask the player the question
print(f"What is {num1} {op} {num2}?")
# Start the timer
start_time = time.time()
player_input = input(f"Your answer (or type 'q' to quit): ")
# Check if the player wants to quit
if player_input.lower() == 'q':
break
# Check if time limit was exceeded
elapsed_time = time.time() - start_time
if elapsed_time > time_limit:
print(f"Time's up! You took too long to answer. The correct answer was {answer}.")
continue
# Check if the answer is correct
try:
player_answer = int(player_input)
if player_answer == answer:
correct_responses = ["Well done!", "Nice job!", "You're on fire!", "Keep it up!"]
print(random.choice(correct_responses))
score += 1
else:
incorrect_responses = [f"Oops! The correct answer was {answer}.",
"Not quite! Try again next time.",
f"Close, but the correct answer was {answer}."]
print(random.choice(incorrect_responses))
except ValueError:
print("Invalid input, please enter a number or 'q' to quit.")
print(f"\nThanks for playing! Your final score is {score}.")
# Start the game
play_game()
Popcorn 2
%%js
// Create a dictionary (object) with different types of fruits
var fruitDictionary = {
1: "Apple",
2: "Banana",
3: "Cherry"
};
// Accessing a value through its corresponding key
console.log("Fruit with key 1:", fruitDictionary[1]); // Output: Apple
console.log("Fruit with key 2:", fruitDictionary[2]); // Output: Banana
console.log("Fruit with key 3:", fruitDictionary[3]); // Output: Cherry
Popcorn 3
# Enhanced Temperature Converter
# Function to convert temperatures
def temperature_converter():
try:
# Prompt the user for the temperature and conversion type
temperature = float(input("Enter the temperature value: "))
conversion_type = input("Convert from (C/F/K): ").strip().upper()
target_type = input("Convert to (C/F/K): ").strip().upper()
# Conversion logic based on user input
if conversion_type == target_type:
print(f"No conversion needed. The temperature remains {temperature:.2f}°{target_type}.")
# Convert from Celsius
elif conversion_type == "C":
if target_type == "F":
fahrenheit = (temperature * 9 / 5) + 32
print(f"{temperature}°C is equal to {fahrenheit:.2f}°F")
elif target_type == "K":
kelvin = temperature + 273.15
print(f"{temperature}°C is equal to {kelvin:.2f}K")
else:
print("Invalid target conversion type.")
# Convert from Fahrenheit
elif conversion_type == "F":
if target_type == "C":
celsius = (temperature - 32) * 5 / 9
print(f"{temperature}°F is equal to {celsius:.2f}°C")
elif target_type == "K":
kelvin = (temperature - 32) * 5 / 9 + 273.15
print(f"{temperature}°F is equal to {kelvin:.2f}K")
else:
print("Invalid target conversion type.")
# Convert from Kelvin
elif conversion_type == "K":
if target_type == "C":
celsius = temperature - 273.15
print(f"{temperature}K is equal to {celsius:.2f}°C")
elif target_type == "F":
fahrenheit = (temperature - 273.15) * 9 / 5 + 32
print(f"{temperature}K is equal to {fahrenheit:.2f}°F")
else:
print("Invalid target conversion type.")
else:
print("Invalid initial conversion type entered. Please use 'C', 'F', or 'K'.")
except ValueError:
print("Invalid input. Please enter a numeric temperature value.")
# Call the temperature converter function
temperature_converter()
Popcorn Hack 1 of 3-4
%%js
let favoriteMovie = "Cars";
let favoriteSport = "cricket";
let petName = "Dot";
let concatenatedMessage = "My favorite movie is " + favoriteMovie + ". I love playing " + favoriteSport + " and my pet's name is " + petName + ".";
let interpolatedMessage = `My favorite movie is ${favoriteMovie}. I love playing ${favoriteSport} and my pet's name is ${petName}.`;
Popcorn Hack 2
%%js
// Define string
let phrase = "A journey of a thousand miles begins with a single step";
// Extraction
let partOne = phrase.slice(2, 9); // "journey" starts at index 2 and ends at index 8, but slice() excludes the end index, so use 9
let partTwo = phrase.slice(-18, -12); // Extracts "miles"
let remainder = phrase.slice(27); // Starts extracting from index 27
// Output
console.log(partOne); // Output: journey
console.log(partTwo); // Output: miles
console.log(remainder); // Output: begins with a single step
Popcorn Hack 3
def remove_vowels(input_str):
vowels = "aeioulAEIOUL"
result = ''.join([char for char in input_str if char not in vowels])
return result
sentence = "I love watching movies with my friends!"
print(remove_vowels(sentence))
Popcorn Hack 4
def reverse_words(input_str):
words = input_str.split()
reversed_words = " ".join(words[::-1])
return reversed_words
sentence1 = "I love coding!"
sentence2 = "Python is amazing"
sentence3 = "A journey of a thousand miles begins with a single step"
print(reverse_words(sentence1))
print(reverse_words(sentence2))
print(reverse_words(sentence3))
Homework for 3-4 and 3-1
Homework for 3-4
%%js
// Function to generate a greeting
function generateGreeting(firstName, lastName) {
// Using string concatenation
let greeting1 = "Hello, " + firstName + " " + lastName + "!";
// Using string interpolation (template literals)
let greeting2 = `Hello, ${firstName} ${lastName}!`;
// Output both greetings
console.log(greeting1); // Concatenation example
console.log(greeting2); // Interpolation example
}
// Test the function
let firstName = "Alex";
let lastName = "Rubio";
generateGreeting(firstName, lastName);
# Function to check if a string is a palindrome
def is_palindrome(input_str):
# Remove spaces and convert to lowercase for uniformity
cleaned_str = input_str.replace(" ", "").lower()
# Check if the string is the same forwards and backwards
return cleaned_str == cleaned_str[::-1]
# Test the function
test_str1 = "racecar"
test_str2 = "A man a plan a canal Panama"
test_str3 = "hello"
print(is_palindrome(test_str1)) # Output: True
print(is_palindrome(test_str2)) # Output: True (ignores spaces and case)
print(is_palindrome(test_str3)) # Output: False
Homework for 3-1
# Conversion rates
CUPS_TO_TABLESPOONS = 16
TABLESPOONS_TO_TEASPOONS = 3
CUPS_TO_TEASPOONS = 48
# Function to convert between units
def convert_ingredient(quantity, from_unit, to_unit):
if from_unit == "cups" and to_unit == "tablespoons":
return quantity * CUPS_TO_TABLESPOONS
elif from_unit == "tablespoons" and to_unit == "cups":
return quantity / CUPS_TO_TABLESPOONS
elif from_unit == "tablespoons" and to_unit == "teaspoons":
return quantity * TABLESPOONS_TO_TEASPOONS
elif from_unit == "teaspoons" and to_unit == "tablespoons":
return quantity / TABLESPOONS_TO_TEASPOONS
elif from_unit == "cups" and to_unit == "teaspoons":
return quantity * CUPS_TO_TEASPOONS
elif from_unit == "teaspoons" and to_unit == "cups":
return quantity / CUPS_TO_TEASPOONS
else:
return "Conversion not available."
# Test the converter
quantity = float(input("Enter the quantity: "))
from_unit = input("Enter the unit you're converting from (cups, tablespoons, teaspoons): ").lower()
to_unit = input("Enter the unit you're converting to (cups, tablespoons, teaspoons): ").lower()
result = convert_ingredient(quantity, from_unit, to_unit)
print(f"{quantity} {from_unit} is equal to {result} {to_unit}.")
# Conversion rates
CUPS_TO_TABLESPOONS = 16
TABLESPOONS_TO_TEASPOONS = 3
CUPS_TO_TEASPOONS = 48
# Function to convert between units
def convert_ingredient(quantity, from_unit, to_unit):
if from_unit == "cups" and to_unit == "tablespoons":
return quantity * CUPS_TO_TABLESPOONS
elif from_unit == "tablespoons" and to_unit == "cups":
return quantity / CUPS_TO_TABLESPOONS
elif from_unit == "tablespoons" and to_unit == "teaspoons":
return quantity * TABLESPOONS_TO_TEASPOONS
elif from_unit == "teaspoons" and to_unit == "tablespoons":
return quantity / TABLESPOONS_TO_TEASPOONS
elif from_unit == "cups" and to_unit == "teaspoons":
return quantity * CUPS_TO_TEASPOONS
elif from_unit == "teaspoons" and to_unit == "cups":
return quantity / CUPS_TO_TEASPOONS
else:
return "Conversion not available."
# Main loop to input ingredients
def ingredient_input_loop():
while True:
# Get ingredient details from the user
ingredient_name = input("Enter the ingredient name (or type 'done' to finish): ").strip().lower()
if ingredient_name == "done":
print("Finished entering ingredients.")
break
try:
quantity = float(input(f"Enter the quantity for {ingredient_name}: "))
from_unit = input("Enter the current unit (cups, tablespoons, teaspoons): ").strip().lower()
to_unit = input("Enter the unit to convert to (cups, tablespoons, teaspoons): ").strip().lower()
# Perform the conversion
result = convert_ingredient(quantity, from_unit, to_unit)
print(f"{quantity} {from_unit} of {ingredient_name} is equal to {result} {to_unit}.\n")
except ValueError:
print("Invalid input. Please enter a numeric value for quantity.\n")
# Run the ingredient input loop
ingredient_input_loop()
# Conversion rates
CUPS_TO_TABLESPOONS = 16
TABLESPOONS_TO_TEASPOONS = 3
CUPS_TO_TEASPOONS = 48
# Function to convert between units
def convert_ingredient(quantity, from_unit, to_unit):
if from_unit == "cups" and to_unit == "tablespoons":
return quantity * CUPS_TO_TABLESPOONS
elif from_unit == "tablespoons" and to_unit == "cups":
return quantity / CUPS_TO_TABLESPOONS
elif from_unit == "tablespoons" and to_unit == "teaspoons":
return quantity * TABLESPOONS_TO_TEASPOONS
elif from_unit == "teaspoons" and to_unit == "tablespoons":
return quantity / TABLESPOONS_TO_TEASPOONS
elif from_unit == "cups" and to_unit == "teaspoons":
return quantity * CUPS_TO_TEASPOONS
elif from_unit == "teaspoons" and to_unit == "cups":
return quantity / CUPS_TO_TEASPOONS
else:
return "Conversion not available."
# Main loop to input ingredients
def ingredient_input_loop():
while True:
# Get ingredient details from the user
ingredient_name = input("Enter the ingredient name (or type 'done' to finish): ").strip().lower()
if ingredient_name == "done":
print("Finished entering ingredients.")
break
try:
# Get the quantity and units for the ingredient
quantity = float(input(f"Enter the quantity for {ingredient_name}: "))
from_unit = input("Enter the current unit (cups, tablespoons, teaspoons): ").strip().lower()
# Ask user for the desired conversion unit
to_unit = input("Enter the unit to convert to (cups, tablespoons, teaspoons): ").strip().lower()
# Perform the conversion
result = convert_ingredient(quantity, from_unit, to_unit)
if isinstance(result, str):
print(result) # Print error message for unavailable conversions
else:
print(f"{quantity} {from_unit} of {ingredient_name} is equal to {result:.2f} {to_unit}.\n")
except ValueError:
print("Invalid input. Please enter a numeric value for quantity.\n")
# Run the ingredient input loop
ingredient_input_loop()
Conversion not available.
Conversion not available.
12.0 teaspoons of bleach is equal to 0.25 cups.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
Invalid input. Please enter a numeric value for quantity.
# Conversion rates
CUPS_TO_TABLESPOONS = 16
TABLESPOONS_TO_TEASPOONS = 3
CUPS_TO_TEASPOONS = 48
# Function to convert between units
def convert_ingredient(quantity, from_unit, to_unit):
if from_unit == "cups" and to_unit == "tablespoons":
return quantity * CUPS_TO_TABLESPOONS
elif from_unit == "tablespoons" and to_unit == "cups":
return quantity / CUPS_TO_TABLESPOONS
elif from_unit == "tablespoons" and to_unit == "teaspoons":
return quantity * TABLESPOONS_TO_TEASPOONS
elif from_unit == "teaspoons" and to_unit == "tablespoons":
return quantity / TABLESPOONS_TO_TEASPOONS
elif from_unit == "cups" and to_unit == "teaspoons":
return quantity * CUPS_TO_TEASPOONS
elif from_unit == "teaspoons" and to_unit == "cups":
return quantity / CUPS_TO_TEASPOONS
else:
return "Conversion not available."
# Main loop to input ingredients
def ingredient_input_loop():
ingredients = [] # List to store ingredients and their conversions
while True:
# Get ingredient details from the user
ingredient_name = input("Enter the ingredient name (or type 'done' to finish): ").strip().lower()
if ingredient_name == "done":
print("Finished entering ingredients.\n")
break
try:
# Get the quantity and units for the ingredient
quantity = float(input(f"Enter the quantity for {ingredient_name}: "))
from_unit = input("Enter the current unit (cups, tablespoons, teaspoons): ").strip().lower()
# Ask user for the desired conversion unit
to_unit = input("Enter the unit to convert to (cups, tablespoons, teaspoons): ").strip().lower()
# Perform the conversion
result = convert_ingredient(quantity, from_unit, to_unit)
if isinstance(result, str):
print(result) # Print error message for unavailable conversions
else:
# Store the original and converted values in the list
ingredients.append({
'name': ingredient_name,
'original_quantity': quantity,
'from_unit': from_unit,
'converted_quantity': result,
'to_unit': to_unit
})
print(f"{quantity} {from_unit} of {ingredient_name} is equal to {result:.2f} {to_unit}.\n")
except ValueError:
print("Invalid input. Please enter a numeric value for quantity.\n")
# Display the summary of conversions
print("\nConversion Summary:")
for ingredient in ingredients:
print(f"{ingredient['original_quantity']} {ingredient['from_unit']} of {ingredient['name']} "
f"= {ingredient['converted_quantity']:.2f} {ingredient['to_unit']}.")
# Run the ingredient input loop
ingredient_input_loop()