# 3.3.3 python popcorn hack
num = int(input())
total_sum = 0
for i in range (1, num +1):
total_sum += i
print(total_sum)
21
#3.3 python popcorn hack #1
#define list of integers
numbers = [2, 35, 14, 27, 10, 19, 52]
#find sum
total_sum = sum(numbers)
#print
print("The sum of the integers is:", total_sum)
The sum of the integers is: 159
#3.3 python popcorn hack #2
#price
price_per_bag = float(input("Enter the price per bag of popcorn: "))
#number of bags
number_of_bags = int(input("Enter the number of bags you want to buy: "))
#total cost
total_cost = price_per_bag * number_of_bags
print(f"The total cost for {number_of_bags} bags of popcorn is: ${total_cost:.2f}")
The total cost for 2 bags of popcorn is: $10.00
#3.3 python big hack
#part 1
function = [39, 18, 41, 27, 4, 17, 31]
#mean code
mean = sum(function) / len(function)
#median code:
inOrder = sorted(function) #sorted function sorts integers from least to greatest
length = len(inOrder)
if length % 2 == 0:
# "%" is a modulo operator, checks if even or odd by dividing by 2 and checking for remainder
median = (inOrder[length // 2 - 1] + inOrder[length // 2]) / 2
else:
median = inOrder [length // 2]
print(f"Mean: {mean}")
print(f"Median: {median}")
#part 2 (collatz problem)
#function starts w var a, lists sequence of numbers in collatz
#start w positive num, if odd: multiply by 3 and add 1, if even: divide by 2
#keep repeating/ iterating process and will always reach 1
#make array to do this and print sequence
def collatz_sequence(n):
# Initialize a list to hold the sequence
sequence = [n]
# Continue the process until n becomes 1
while n != 1:
if n % 2 == 0: # If n is even
n = n // 2
else: # If n is odd
n = n * 3 + 1
sequence.append(n) # Append the new value of n to the sequence
return sequence
# Get user input
try:
user_input = int(input("Enter a positive integer: "))
if user_input <= 0:
raise ValueError("The number must be positive.")
except ValueError as e:
print(f"Invalid input: {e}")
else:
# Calculate the Collatz sequence
result_sequence = collatz_sequence(user_input)
# Display the result
print("The Collatz sequence is:")
print(" -> ".join(map(str, result_sequence)))
Mean: 25.285714285714285
Median: 27
The Collatz sequence is:
74 -> 37 -> 112 -> 56 -> 28 -> 14 -> 7 -> 22 -> 11 -> 34 -> 17 -> 52 -> 26 -> 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
%%javascript
//3.3.4 js popcorn hack #1
function Number32() {
let thirtyTwo = (1+2) * 22 - 2 / 2;
return thirtyTwo;
}
console.log(getNumber32());
<IPython.core.display.Javascript object>
%%javascript
//3.3 js popcorn hack #2
function makeSandwich() {
let ingredients = [];
let ingredient = prompt("Enter an ingredient for your sandwich (or type 'done' to finish):");
while (ingredient.toLowerCase() !== 'done') {
ingredients.push(ingredient);
ingredient = prompt("Enter another ingredient (or type 'done' to finish):");
}
// Combine ingredients
let sandwichName = ingredients.join(" ") + " sandwich";
console.log(`You created a: ${sandwichName}`);
}
// Call the function to make a sandwich
makeSandwich();
<IPython.core.display.Javascript object>
%%javascript
//3.3 js big hack
function computeGCDandLCM(a, b) {
// Function to compute GCD using the Euclidean algorithm
function gcd(x, y) {
while (y !== 0) {
let temp = y;
y = x % y;
x = temp;
}
return x;
}
// Function to compute LCM
function lcm(x, y) {
return (x * y) / gcd(x, y);
}
// GCD and LCM
const greatestCommonDivisor = gcd(a, b);
const leastCommonMultiple = lcm(a, b);
// Return results as an object
return {
gcd: greatestCommonDivisor,
lcm: leastCommonMultiple
};
}
const a = 12;
const b = 18;
const result = computeGCDandLCM(a, b);
console.log(result); // { gcd: 6, lcm: 36 }
<IPython.core.display.Javascript object>
#3.5.3 python popcorn hack #1
def check_number():
try:
number = float(input("Please enter a number: ")) #float is number that's not an integer
if number < 0:
print("The is a negative number!")
else:
print("The is a non-negative number!")
except ValueError:
print("Invalid input! Please enter a valid number.")
check_number()
The is a negative number!
#3.5.3 python popcorn hack #2
def check_scores(score1, score2):
if score1 >= 70 and score2 >= 70:
print("The student passed both subjects.")
else:
print("The student did not pass both subjects.")
score1 = float(input("Enter the first score: "))
score2 = float(input("Enter the second score: "))
check_scores(score1, score2)
The student did not pass both subjects.
#3.5.3 python popcorn hack #3
def vowel_check (char):
vowels = "aeiou"
if char.lower() in vowels:
print(f"The character '{char}' is a vowel")
else:
print(f"The character '{char}' is not a vowel")
char = input("Enter a character: ")
if len(char) == 1:
vowel_check(char)
else:
print("Please enter a single character.")
The character 'u' is a vowel
%%javascript
//3.5.4 js popcorn hack
function evenOrOdd(number) {
if (number % 2 === 0) {
return `${number} is even.`;
} else {
return `${number} is odd.`;
}
}
console.log(evenOrOdd(4));
console.log(evenOrOdd(7));
<IPython.core.display.Javascript object>
%%javascript
//3.5.4 js big hack (i did password creator hack)
function checkPassword(password) {
const minLength = 10;
if (!(password.length >= minLength &&
/[A-Z]/.test(password) &&
/[a-z]/.test(password) &&
/\d/.test(password) &&
!/\s/.test(password))) {
return "Password invalid. Must have 10 characters, at least one number, at least one uppercase, and no spaces!";
} else {
return "Password is secure and set!";
}
}
const userPassword = prompt("Enter your password:");
const result = checkPassword(userPassword);
alert(result);
<IPython.core.display.Javascript object>
#3.5.3 python main hack
def play_game():
print("Welcome to the Game!")
# Define the levels with puzzles and correct answers
levels = [
{
"puzzle": "A: is the sky is light blue or B: dark blue?",
"correct_answer": "A",
},
{
"puzzle": "Is homecoming on A: Octobor 12 or B: October 13?",
"correct_answer": "A",
},
{
"puzzle": "Does the AP Course Mr. Liao teaches A: AP physics E&M or B: AP physics C: Mechanics?",
"correct_answer": "B",
},
]
# Loop through each level
for level in levels:
print(f"\nLevel {levels.index(level) + 1}: Solve the puzzle!")
print(f"Solve: {level['puzzle']}")
while True:
player_answer = input("Your Answer (e.g., 'A' or 'B'): ").strip()
# First, check if input is valid (either 'A' or 'B')
if player_answer not in ["A", "B"]:
print("Invalid input, please try again.")
continue # Prompt the player to try again
# Check if the player's answer is correct for this level
if player_answer == level["correct_answer"]:
print("Correct!")
break # Move to the next level
else:
print("Incorrect. The correct answer is:", level['correct_answer'])
break # Move to the next level
else:
print("\nYou've reached the end of the game! See you again")
if __name__ == "__main__":
play_game()
Welcome to the De Morgan's Law Game!
Level 1: Solve the puzzle!
Solve: A: is the sky is light blue or B: dark blue?
Correct!
Level 2: Solve the puzzle!
Solve: Is homecoming on A: Octobor 12 or B: October 13?
Incorrect. The correct answer is: A
Level 3: Solve the puzzle!
Solve: Does the AP Course Mr. Liao teaches A: AP physics E&M or B: AP physics C: Mechanics?
Correct!
You've reached the end of the game! See you again
user_input = input("Enter multiple sentences or words: ")
# Step 2: Display original string
print("\nOriginal String:")
print(user_input)
# Step 3: Count total characters (including spaces)
total_characters = len(user_input)
print(f"\nTotal characters (including spaces): {total_characters}")
# Step 4: Find the longest word and its character length
words = user_input.split() # Split the input into words
longest_word = max(words, key=len)
print(f"\nLongest word: '{longest_word}' with {len(longest_word)} characters")
# Step 5: Display the string reversed
reversed_string = user_input[::-1]
print("\nReversed String:")
print(reversed_string)
# Step 6: Find the middle word/character (excluding spaces and special characters)
import re
# Remove spaces and special characters
cleaned_string = re.sub(r'[^A-Za-z0-9]+', '', user_input)
total_clean_characters = len(cleaned_string)
# Find the middle character
middle_index = total_clean_characters // 2
middle_character = cleaned_string[middle_index]
print(f"\nMiddle character (excluding spaces and special characters): '{middle_character}'")
# Step 7: Find the middle word
if len(words) % 2 == 0:
middle_word = words[len(words) // 2 - 1]
else:
middle_word = words[len(words) // 2]
print(f"\nMiddle word: '{middle_word}'")
Original String:
hi this is a sample test and seeing if it works 123 ***
Total characters (including spaces): 55
Longest word: 'sample' with 6 characters
Reversed String:
*** 321 skrow ti fi gniees dna tset elpmas a si siht ih
Middle character (excluding spaces and special characters): 'n'
Middle word: 'and'