# Popcorn Hack 1: Prompt the user to enter a number n. Initialize total_sum to 0. Use a loop to iterate from 1 to n. Add each number to total_sum. Print the total_sum. (Python)
# Function to get valid integer input
def integer():
while True:
try:
n = int(input("Enter a number: "))
return n # If input is valid, return the number
except ValueError:
print("Invalid input. Please enter a valid integer.")
# Get a valid number from the user
n = integer()
# Initialize total_sum to 0
total_sum = 0
# Use a loop to iterate from 1 to n and add each number to total_sum
for i in range(1, n + 1):
total_sum += i
#Homework Hack 1
import statistics
def compute_mean_and_median(numbers):
# Compute the arithmetic mean
mean = statistics.mean(numbers)
# Compute the median
median = statistics.median(numbers)
# Print the results
print(f"Arithmetic Mean: {mean}")
print(f"Median: {median}")
# Example usage
numbers = [10, 20, 30, 40, 50]
compute_mean_and_median(numbers)
def collatz_sequence(a):
sequence = [a] # Start the sequence with the initial value a
# Loop until the value of a becomes 1
while a != 1:
if a % 2 == 0:
a = a // 2 # If a is even, divide by 2
else:
a = 3 * a + 1 # If a is odd, multiply by 3 and add 1
sequence.append(a) # Add the result to the sequence
# Print the sequence
print("Collatz sequence:", sequence)
# Example usage
collatz_sequence(13)
Arithmetic Mean: 30
Median: 30
Collatz sequence: [13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
#Extra Python Practice: Iteration and Repetition
# Iteration: Using a for loop to iterate over a list
def iterate_over_list():
fruits = ["apple", "banana", "cherry", "date"]
print("List of fruits:")
for fruit in fruits:
print(fruit)
# Repetition: Using a while loop to repeat an action
def repeat_until_condition():
counter = 0
while counter < 5:
print(f"Repetition {counter + 1}: TWhat is your favorite fruit?")
counter += 1
# Calling the functions
iterate_over_list()
repeat_until_condition()
List of fruits:
apple
banana
cherry
date
Repetition 1: TWhat is your favorite fruit?
Repetition 2: TWhat is your favorite fruit?
Repetition 3: TWhat is your favorite fruit?
Repetition 4: TWhat is your favorite fruit?
Repetition 5: TWhat is your favorite fruit?
%%js
// Popcorn Hack 2: Create a function that uses 4 of the 5 basic arithmetic operations and returns the number 32 as the answer. (Javascript)
function calculate32() {
// Using four arithmetic operations: +, -, *, /
let result = (8 * 5) - (4 / 2) + 6; // 8*5 = 40, 4/2 = 2, 40 - 2 + 6 = 44
result = result - 12; // Final adjustment to get 32 (44 - 12 = 32)
return result;
}
// Call the function and log the result
console.log(calculate32()); // Output: 32
<IPython.core.display.Javascript object>
%%js
//Homework Hack 2
function gcdAndLcm(a, b) {
// Helper function to compute GCD using Euclidean algorithm
function gcd(x, y) {
while (y !== 0) {
let temp = y;
y = x % y;
x = temp;
}
return x;
}
// Compute the GCD
let gcdResult = gcd(a, b);
// Compute the LCM using the relationship: LCM(a, b) = |a * b| / GCD(a, b)
let lcmResult = Math.abs(a * b) / gcdResult;
// Return both GCD and LCM as an object
return {
gcd: gcdResult,
lcm: lcmResult
};
}
// Example usage
console.log(gcdAndLcm(12, 18)); // Output: { gcd: 6, lcm: 36 }
<IPython.core.display.Javascript object>
%%js
//Extra JS Practice: Grocery Prices
// Function to calculate the total price with 8% sales tax
function groceryPriceCalculator() {
// Ask the user for the price of three items
let item1 = parseFloat(prompt("Enter the price of item 1:"));
let item2 = parseFloat(prompt("Enter the price of item 2:"));
let item3 = parseFloat(prompt("Enter the price of item 3:"));
// Check if the inputs are valid numbers
if (isNaN(item1) || isNaN(item2) || isNaN(item3)) {
alert("Please enter valid prices for all items.");
return;
}
// Sales tax rate (8%)
const salesTaxRate = 0.08;
// Calculate the price with tax for each item
let totalItem1 = item1 + (item1 * salesTaxRate);
let totalItem2 = item2 + (item2 * salesTaxRate);
let totalItem3 = item3 + (item3 * salesTaxRate);
// Calculate the total price for all items
let totalPrice = totalItem1 + totalItem2 + totalItem3;
// Output the total price
alert("The total price with tax for all items is: $" + totalPrice.toFixed(2));
}
// Call the function to run the calculator
groceryPriceCalculator();
<IPython.core.display.Javascript object>