Homework and Popcorn Hacks for 3.1
Homeworks and Popcorn Hacks
Popcorn Hack 1.1 - Simple Dictionary
%%js
var myDictionary = {
1: "fruit",
2: "fruit",
3: "fruit"
};
// Accessing a value
console.log("Fruit with key 2:", myDictionary[2]); // Output: fruit
Popcorn Hack 1.2 - Simple Calculator with tweaks
import random
import time
def play_game():
score = 0
operators = ['+', '-', '*', '/'] # Added division
max_time = 10 # Time limit for each question
print("Welcome to the Math Game!")
print("Answer as many questions as you can within the time limit of 10 seconds.")
print("Type 'q' to quit at any time.\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)
# Calculate the correct answer based on the operator
if op == '+':
answer = num1 + num2
elif op == '-':
answer = num1 - num2
elif op == '*':
answer = num1 * num2
elif op == '/':
# Ensure no division by zero
num2 = random.randint(1, 10) # Make sure num2 is not zero
answer = round(num1 / num2, 2) # Round to 2 decimal places
# Ask the player the question
print(f"What is {num1} {op} {num2}?")
start_time = time.time() # Start the timer
player_input = input("Your answer (or type 'q' to quit): ")
# Check if the player wants to quit
if player_input.lower() == 'q':
break
elapsed_time = time.time() - start_time # Check elapsed time
if elapsed_time > max_time:
print(f"Time's up! You took too long. The correct answer was {answer}.")
continue
# Check if the answer is correct
try:
player_answer = float(player_input) # Use float for division
if abs(player_answer - answer) < 0.01: # Allow for rounding errors
print("Correct! Great job!")
score += 1
else:
print(f"Oops! The correct answer was {answer}.")
except ValueError:
print("Invalid input, please enter a number or 'q' to quit.")
print(f"Thanks for playing! Your final score is {score}.")
# Start the game
play_game()
Welcome to the Math Game!
Answer as many questions as you can within the time limit of 10 seconds.
Type 'q' to quit at any time.
What is 1 + 9?
Correct! Great job!
What is 9 - 10?
Correct! Great job!
What is 7 + 3?
Correct! Great job!
What is 10 / 1?
Correct! Great job!
What is 5 * 8?
Oops! The correct answer was 40.
What is 9 - 2?
Correct! Great job!
What is 5 / 4?
Thanks for playing! Your final score is 5.
Popcorn Hack 1.3 - Temperature converter in JS and Python
%%js
// Temperature Converter in JavaScript
function convertTemperature() {
let temperature = parseFloat(prompt("Enter the temperature:"));
if (isNaN(temperature)) return console.log("Invalid number.");
let type = prompt("Convert to (C)elsius or (F)ahrenheit?").toUpperCase();
let result;
if (type === "C") {
result = (temperature - 32) * (5 / 9);
console.log(`${temperature}°F = ${result.toFixed(2)}°C`);
} else if (type === "F") {
result = (temperature * (9 / 5)) + 32;
console.log(`${temperature}°C = ${result.toFixed(2)}°F`);
} else {
console.log("Invalid type. Use 'C' or 'F'.");
}
}
// Loop for continuous conversion
do {
convertTemperature();
} while (confirm("Convert another temperature?"));
<IPython.core.display.Javascript object>
def temperature_converter():
try:
temperature = float(input("Enter the temperature: "))
conversion_type = input("Convert to Celsius (C) or Fahrenheit (F)? ").strip().upper()
if conversion_type == "C":
celsius = (temperature - 32) * (5 / 9)
print(f"{temperature}°F is equal to {celsius:.2f}°C")
elif conversion_type == "F":
fahrenheit = (temperature * (9 / 5)) + 32
print(f"{temperature}°C is equal to {fahrenheit:.2f}°F")
else:
print("Invalid conversion type entered. Please enter 'C' or 'F'.")
except ValueError:
print("Invalid input. Please enter a numeric temperature value.")
temperature_converter()
56.0°F is equal to 13.33°C
Popcorn Hack 4.1
%%javascript
let favoritesong = "Misses";
let favoritecar = "Mercedes G-Wagon";
let foodtype = "Dessert";
let concatenatedmessage = "My Favorite song is" + favoritesong + "I love the" + favoritecar + "and my favorite type of food is" + foodtype
console.log(concatenatedmessage)
<IPython.core.display.Javascript object>
Popcorn Hack 4.2
%%js
let phrase = "Its not about the destination its about the journey and how you goth there";
let partOne = phrase.slice(2, 8);
let partTwo = phrase.slice(-18,-12);
let remainder = phrase.slice(20);
console.log(partOne);
console.log(partTwo);
console.log(remainder);
<IPython.core.display.Javascript object>
Popcorn Hack 4.3
def removal_vowels(input_str):
vowels = "darshDARSH"
result = ''.join([char for char in input_str if char not in vowels])
return result
sentence = "I love playing Badminton"
print(removal_vowels(sentence))
I love plying Bminton
Reverse Hack (also a popcorn hack)
def words_reverse(input_str):
words = input_str.split()
words_reverse = " ".join(words[::-1])
return words_reverse
sentence = "Travis Scott is the best!!!"
print(words_reverse(sentence))
best!!! the is Scott Travis
Homework Hack 1
Part 1
shopping_list = []
total_cost = 0.0
print("Shopping List:", shopping_list)
print("Total Cost: $", total_cost)
Shopping List: []
Total Cost: $ 0.0
Part 2
shopping_list = []
total_cost = 0.0
while True:
item_name = input("Enter item name (or 'done' to finish): ")
if item_name.lower() == 'done':
break
try:
item_price = float(input(f"Enter price for '{item_name}': "))
shopping_list.append((item_name, item_price))
total_cost += item_price
print(f"Added '{item_name}' at ${item_price:.2f}.")
except ValueError:
print("Invalid price. Please enter a number.")
print("\nShopping List:")
for item, price in shopping_list:
print(f"{item}: ${price:.2f}")
print(f"Total Cost: ${total_cost:.2f}")
Added 'Cake' at $12.00.
Added 'Chocolate' at $2.00.
Added 'Sauce' at $3.00.
Added 'Chicken' at $1000.00.
Shopping List:
Cake: $12.00
Chocolate: $2.00
Sauce: $3.00
Chicken: $1000.00
Total Cost: $1017.00
Homework Hack 2
cup_to_tbsp, tbsp_to_tsp = 16, 3
cup_to_tsp = cup_to_tbsp * tbsp_to_tsp
def convert_ingredient(quantity, from_unit, to_unit):
if from_unit == "cup":
return quantity * (cup_to_tbsp if to_unit == "tbsp" else cup_to_tsp)
elif from_unit == "tbsp":
return quantity / (cup_to_tbsp if to_unit == "cup" else 1) * (tbsp_to_tsp if to_unit == "tsp" else 1)
elif from_unit == "tsp":
return quantity / (cup_to_tsp if to_unit == "cup" else tbsp_to_tsp)
ingredients = []
while True:
name = input("Ingredient name (or 'done' to finish): ")
if name.lower() == 'done': break
quantity = float(input("Quantity: "))
unit = input("Current unit (cup/tbsp/tsp): ").strip().lower()
desired_unit = input("Convert to (cup/tbsp/tsp): ").strip().lower()
ingredients.append((name, quantity, unit, desired_unit))
for name, quantity, unit, desired_unit in ingredients:
converted = convert_ingredient(quantity, unit, desired_unit)
print(f"{quantity} {unit} of {name} = {converted:.2f} {desired_unit}.")
2.0 tbsp of Cheese = 6.00 tsp.