<IPython.core.display.Javascript object>
#PYTHON HACK 1
#Define a list of integers
integers = [2, 8, 14, 21, 33]
#Function to calculate arithmetic mean
def calculate_mean(numbers):
return sum(numbers) / len(numbers)
#Function to calculate median
def calculate_median(numbers):
sorted_numbers = sorted(numbers)
mid_index = len(sorted_numbers) // 2
#use the middle element
return sorted_numbers[mid_index]
#Calculate mean and median
mean = calculate_mean(integers)
median = calculate_median(integers)
#Print the results
print("Arithmetic Mean:", mean)
print("Median:", median)
Arithmetic Mean: 15.6
Median: 14
[7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
%%js
//JAVASCRIPT HACK 1
//Function to find the GCD of two numbers
function findGCD(a, b) {
while (b !== 0) {
[a, b] = [b, a % b]; //Swap the values of a and b
}
return a; //When b becomes 0, a is the GCD
}
//Function to find the LCM of two numbers
function findLCM(a, b) {
return Math.abs(a * b) / findGCD(a, b); // a * b / GCD = LCM
}
//Function to return both GCD and LCM as an object
function gcdAndLcm(a, b) {
const gcd = findGCD(a, b); //Find GCD
const lcm = findLCM(a, b); //Find LCM
return { GCD: gcd, LCM: lcm }; //Return both as an object
}
//Define a and b
let a = 1;
let b = 7;
//Call the function and print the result
console.log(gcdAndLcm(a, b)); //output {GCD: 1, LCM: 14}
<IPython.core.display.Javascript object>
<IPython.core.display.Javascript object>
<IPython.core.display.Javascript object>
#PYTHON HACK 1
def generate_truth_table(variables, expression):
# Number of rows is 2 to power of # of variables!
num_rows = 2 ** len(variables)
# Print header
print(f"{' | '.join(variables)} | {expression}")
print('-' * (len(variables) * 4 + len(expression) + 3))
# Loop through each row (from 0 to 2^n - 1)
for i in range(num_rows):
# Generate binary values (0 or 1) for each variable
values = [(i >> j) & 1 for j in range(len(variables) - 1, -1, -1)]
# truth values
truth_values = [bool(val) for val in values]
# dictionary of variable values
value_dict = dict(zip(variables, truth_values))
# look at expression using the variable values
result = eval(expression, {}, value_dict)
# Print the rows of the truth table
row = ' | '.join(str(value_dict[var]) for var in variables)
print(f"{row} | {result}")
# tet variables
variables = ['A', 'B']
expression = '(A and B) or not A'
generate_truth_table(variables, expression)
A | B | (A and B) or not A
-----------------------------
False | False | True
False | True | True
True | False | False
True | True | True
#PYTHON HACK 2
# using De Morgan's Law to check answer
def check_answer(question, player_answer):
if question == "Is 2 + 2 equal to 4?":
# Correct answer yes
return not (player_answer != "yes") # Applying De Morgan's Law: not (A and B) is the same as (not A) or (not B)
elif question == "Is the sky green?":
# Correct answer no
return not (player_answer != "no") # Applying De Morgan's Law here to simplify logic
elif question == "Is fire cold?":
# Correct answer no
return not (player_answer != "no") # Another example of simplifying with De Morgan's Law
else:
# If the question is unknown, just return False
return False
# List of questions
questions = [
"Is 2 + 2 equal to 4?",
"Is the sky green?",
"Is fire cold?"
]
# Game logic
def game():
print("Welcome to the De Morgan's Law Game!")
score = 0
total_questions = len(questions)
# Ask each question
for i in range(total_questions):
question = random.choice(questions)
print(f"Question {i+1}: {question}")
player_answer = input("Answer (yes/no): ").lower()
# Ensure valid input
if player_answer not in ["yes", "no"]:
print("Invalid answer! Please enter 'yes' or 'no'.")
continue
# Check the answer using De Morgan's Law logic
if check_answer(question, player_answer):
print("Correct!")
score += 1
else:
print("Incorrect.")
# End of the game
print(f"Game over! Your score: {score}/{total_questions}")
# Start the game
if __name__ == "__main__":
game()
Welcome to the De Morgan's Law Game!
Question 1: Is fire cold?
Correct!
Question 2: Is 2 + 2 equal to 4?
Incorrect.
Question 3: Is the sky green?
Correct!
Game over! Your score: 2/3
<IPython.core.display.Javascript object>
%%js
//JAVASCRIPT HACK 2
function personalityQuiz() {
let score = 0;
// Array of 10 questions
const questions = [
"1. How do you prefer to spend your free time?\n1. Reading a book\n2. Hanging out with friends\n3. Exploring outdoors",
"2. Which describes you best?\n1. Calm and thoughtful\n2. Social and outgoing\n3. Adventurous and active",
"3. What is your favorite type of movie?\n1. Documentaries or dramas\n2. Comedies or romantic movies\n3. Action or adventure",
"4. How do you handle stress?\n1. Stay calm and think it through\n2. Talk to friends\n3. Do something active to blow off steam",
"5. What do you value most?\n1. Knowledge\n2. Relationships\n3. Freedom",
"6. Which activity sounds the most fun to you?\n1. Solving a puzzle\n2. Attending a party\n3. Going hiking",
"7. What is your ideal vacation?\n1. Visiting a museum or historical site\n2. Going on a group tour with friends\n3. An outdoor adventure like camping or climbing",
"8. How do you make decisions?\n1. Carefully weigh all options\n2. Ask for advice from others\n3. Go with your gut instinct",
"9. What motivates you?\n1. Learning something new\n2. Connecting with people\n3. Experiencing excitement",
"10. How would your friends describe you?\n1. Thoughtful\n2. Fun-loving\n3. Adventurous"
];
// Ask each question and update score
for (let i = 0; i < questions.length; i++) {
let answer = prompt(questions[i]);
score += parseInt(answer); // Add the user's answer to the total score
}
// Personality result based on score
if (score <= 15) {
console.log("You are introspective and prefer quiet environments. You enjoy thinking deeply and spending time in calm, peaceful settings.");
} else if (score <= 25) {
console.log("You are social and enjoy spending time with others. You thrive in group settings and enjoy being around people.");
} else {
console.log("You are adventurous and always seeking excitement! You love trying new things and exploring the world around you.");
}
}
personalityQuiz();
//when run it will promp you to awsner all the questions entering a number for your awsner
//it will add up all the scores to show your final score/personality
<IPython.core.display.Javascript object>