Popcorn Hacks
# List of x-coordinates to be plugged into the equation to get the corresponding y-values
x_values = [2, 5, 7, 10]
# Loop to iterate through the list of x-coordinates
for x in x_values:
# Calculate the corresponding y-values using the equation f(x) = 2(x - 3)^2 + 5
y = 2 * (x - 3) ** 2 + 5
# Print the result for each x-coordinate
print(f"f({x}) = {y}")
f(2) = 7
f(5) = 13
f(7) = 37
f(10) = 103
numb1 = 40
numb2 = numb1 /4
numb3 = numb2 * 10 + 3
print(numb3)
103.0
a, b = 100, 99
Add = a + b
Subtract = a - b
Multiply = a * b
Divide = a / b if b != 0 else 'undefined'
print(f"Add: {Add}")
print(f"Subtract: {Subtract}")
print(f"Multiply: {Multiply}")
print(f"Divide: {Divide}")
Add: 199
Subtract: 1
Multiply: 9900
Divide: 1.0101010101010102
def fibonacci(n):
if n <= 0:
return "invalid"
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
n = 5
print(f"The {n}th Fibonacci number is: {fibonacci(n)}")
The 5th Fibonacci number is: 3
def A():
return True # Condition A
def B():
return True # Condition B
# Original statement: if A then B
if A():
print("A is true, so B must also be true:", B())
else:
print("A is false, we cannot conclude anything about B.")
# Contrapositive: if not B then not A
if not B():
print("B is false, therefore A must also be false:", not A())
else:
print("B is true, we cannot conclude anything about A.")
A is true, so B must also be true: True
B is true, we cannot conclude anything about A.
Homework Hacks
Alternate Fibonacci Implementation
fibonacci = [0, 1]
num = int(input("Enter the number until which you want to calculate: "))
# subtract one to account for preset fibonacci numbers
for i in range(num):
fibonacci.append(fibonacci[i] + fibonacci[i + 1])
if len(fibonacci) == num:
break
print(fibonacci[-1])
3
import numpy as np
import logging
import sys
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(message)s')
def matrix_multiply(A, B):
"""
Perform matrix multiplication between two numpy arrays A and B.
"""
logging.debug(f"Multiplying matrices:\n{A}\n{B}")
return np.dot(A, B)
def matrix_power(M, power):
"""
Raise matrix M to the specified power using binary exponentiation.
"""
if power < 0:
raise ValueError("Power must be a non-negative integer.")
result = np.identity(len(M), dtype=object)
logging.debug(f"Initial identity matrix:\n{result}")
while power > 0:
if power % 2 == 1:
result = matrix_multiply(result, M)
logging.debug(f"Result after multiplying by M:\n{result}")
M = matrix_multiply(M, M)
logging.debug(f"Matrix M squared:\n{M}")
power = power // 2
logging.debug(f"Power reduced to: {power}")
return result
def fibonacci_matrix(n):
"""
Calculate the nth Fibonacci number using matrix exponentiation.
"""
if not isinstance(n, int):
raise TypeError("Input must be an integer.")
if n < 0:
raise ValueError("Fibonacci number is not defined for negative integers.")
elif n == 0:
return 0
elif n == 1:
return 1
F = np.array([[1, 1],
[1, 0]], dtype=object)
result = matrix_power(F, n-1)
logging.info(f"Matrix raised to power {n-1}:\n{result}")
return result[0][0]
def validate_input(user_input):
"""
Validate the user input to ensure it's a non-negative integer.
"""
try:
value = int(user_input)
if value < 0:
raise ValueError
return value
except ValueError:
raise ValueError("Please enter a valid non-negative integer.")
def main():
"""
Main function to execute the Fibonacci calculation.
"""
try:
user_input = input("Enter the position of the Fibonacci number you want to calculate: ")
n = validate_input(user_input)
fib_n = fibonacci_matrix(n)
print(f"Fibonacci number at position {n} is: {fib_n}")
except ValueError as ve:
logging.error(ve)
except Exception as e:
logging.error(f"An unexpected error occurred: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
INFO:Matrix raised to power 7:
[[21 13]
[13 8]]
Fibonacci number at position 8 is: 21
%%js
class FibonacciDP {
static fibonacci(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let prev1 = 1, prev2 = 0;
let current = 0;
for (let i = 2; i <= n; i++) {
current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
return current;
}
static fibonacciMatrix(n) {
if (n === 0) return 0;
let F = [[1, 1], [1, 0]];
this.power(F, n - 1);
return F[0][0];
}
static power(F, n) {
if (n === 0 || n === 1) return;
let M = [[1, 1], [1, 0]];
this.power(F, Math.floor(n / 2));
this.multiply(F, F);
if (n % 2 !== 0) this.multiply(F, M);
}
static multiply(F, M) {
let x = F[0][0] * M[0][0] + F[0][1] * M[1][0];
let y = F[0][0] * M[0][1] + F[0][1] * M[1][1];
let z = F[1][0] * M[0][0] + F[1][1] * M[1][0];
let w = F[1][0] * M[0][1] + F[1][1] * M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
}
let n = 50;
console.log(`Fibonacci number at position ${n} using one method is: ` + FibonacciDP.fibonacci(n));
console.log(`Fibonacci number at position ${n} using alternate method is: ` + FibonacciDP.fibonacciMatrix(n));
<IPython.core.display.Javascript object>
def AND(A, B):
return A and B
def OR(A, B):
return A or B
def NOT(A):
return not A
print("A B | AND | OR | NOT A")
print("---------------------------")
for A in [True, False]:
for B in [True, False]:
print(f"{A:<5} {B:<5} | {AND(A, B):<4} | {OR(A, B):<3} | {NOT(A)}")
A B | AND | OR | NOT A
---------------------------
1 1 | 1 | 1 | False
1 0 | 0 | 1 | False
0 1 | 0 | 1 | True
0 0 | 0 | 0 | True
%%js
class LogicGateSimulator {
// Define logic gate functions
static AND(A, B) {
return A && B;
}
static OR(A, B) {
return A || B;
}
static NOT(A) {
return !A;
}
static NAND(A, B) {
return !(A && B);
}
static NOR(A, B) {
return !(A || B);
}
static XOR(A, B) {
return A ^ B;
}
static displayGateOperations(A, B) {
console.log(`A: ${A}, B: ${B}`);
console.log(`AND: ${LogicGateSimulator.AND(A, B)}`);
console.log(`OR: ${LogicGateSimulator.OR(A, B)}`);
console.log(`NOT A: ${LogicGateSimulator.NOT(A)}`);
console.log(`NAND: ${LogicGateSimulator.NAND(A, B)}`);
console.log(`NOR: ${LogicGateSimulator.NOR(A, B)}`);
console.log(`XOR: ${LogicGateSimulator.XOR(A, B)}`);
console.log("-----------------------------");
}
static main() {
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
console.log("Logic Gate Simulator");
console.log("Enter 'exit' to quit");
const askQuestions = () => {
readline.question("Enter value for A (true/false): ", (A_input) => {
if (A_input.trim().toLowerCase() === "exit") {
readline.close();
return;
}
readline.question("Enter value for B (true/false): ", (B_input) => {
if (B_input.trim().toLowerCase() === "exit") {
readline.close();
return;
}
const A = A_input.trim().toLowerCase() === 'true';
const B = B_input.trim().toLowerCase() === 'true';
LogicGateSimulator.displayGateOperations(A, B);
askQuestions();
});
});
};
askQuestions();
}
}
LogicGateSimulator.main();
<IPython.core.display.Javascript object>
def A():
return True # Condition A
def B():
return True # Condition B
# Original statement: if A then B
if A():
print("A is true, so B must also be true:", B())
else:
print("A is false, we cannot conclude anything about B.")
# Contrapositive: if not B then not A
if not B():
print("B is false, therefore A must also be false:", not A())
else:
print("B is true, we cannot conclude anything about A.")
Contrapositive Law Explanation
The contrapositive law states that an if-then statement is only true if its contrapositive is true. The contrapositive of an if-then statement is the statement negated and inverted. For example:
Original: If I eat 100 donuts, then I will get sick. Contrapositive: If I don’t get sick, then I don’t eat 100 donuts.
Contrapositive is an example of booleans as it relies on True and False Statements.
De Morgan’s Law Explanation
De Morgan’s first law: The complement of the union of two sets is the intersection of their complements.
Regular English Equivalent: Not (A and B) is the same as Not A or Not B.
Statement: “It’s not true that I will eat cake and ice cream.” Applying De Morgan’s First Law: “Either I will not eat pizza or I will not eat ice cream.”
De Morgan’s second law: The complement of the intersection of two sets is the union of their complements.
Regular English Equivalent: Not (A or B) is the same as Not A and Not B.
Statement: “It’s not true that I will eat a cake or eat a ice cream.” Applying De Morgan’s Second Law: “I will neither eat cake nor eat icecream.”
Use Cases of De Morgan’s Laws: Can help in Math and CS for logical tasks, circuit design, etc.
%%js
// same as not(a and b)
if (!(isRaining && isCold)) {
console.log("It's either not raining or not cold.");
}
// shows not A or Not B, as ! represents not and the || represents or.
if (!isRaining || !isCold) {
console.log("It's either not raining or not cold.");
}
<IPython.core.display.Javascript object>