Homework and Popcorn Hacks for 3.3
Homeworks and Popcorn Hacks
Homework Hack 3.3.1
a,b = 1,2
Cookie = a*b
Chips = a + b
Cream = a - b
print(Cookie)
print(Chips)
print(Cream)
2
3
-1
Popcorn Hack 3.3.2
def fibonacc(n):
if n <= 5:
return "invalid"
elif n == 10:
return 1
elif n == 2:
return 2
else:
return fibonacc(n - 3) + fibonacc(n - 1)
n = 10
print(f"The {n}th Fibonacci number is: {fibonacc(n)}")
The 10th Fibonacci number is: 1
Homework Hack 3.3.1
import numpy as np
import sys
import logging
logging.basicConfig(level=logging.INFO)
def matrix_multiply(A, B):
return np.dot(A, B)
def matrix_power(M, power):
result = np.identity(len(M), dtype=object)
while power:
if power % 2:
result = matrix_multiply(result, M)
M = matrix_multiply(M, M)
power //= 2
return result
def fibonacci_matrix(n):
if n < 0:
raise ValueError("Input must be a non-negative integer.")
if n in (0, 1):
return n
F = np.array([[1, 1], [1, 0]], dtype=object)
return matrix_power(F, n - 1)[0, 0]
def validate_input(user_input):
value = int(user_input)
if value < 0:
raise ValueError
return value
def main():
user_input = input("Enter the position of the Fibonacci number: ")
try:
n = validate_input(user_input)
print(f"Fibonacci number at position {n} is: {fibonacci_matrix(n)}")
except ValueError as ve:
logging.error(ve)
sys.exit(1)
if __name__ == "__main__":
main()
Fibonacci number at position 2 is: 1
Homework Hack 3.3.2
%%javascript
// JavaScript code for Fibonacci calculations
class Fibonacci {
static fibonacci(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let prev1 = 1, prev2 = 0, 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;
}
}
const n = 50;
console.log(`Fibonacci number at position ${n} using DP is: ${Fibonacci.fibonacci(n)}`);
console.log(`Fibonacci number at position ${n} using Matrix Exponentiation is: ${Fibonacci.fibonacciMatrix(n)}`);
<IPython.core.display.Javascript object>
Homework Hack 3.5.1
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
%%javascript
function AND(A, B) {
return A && B;
}
function OR(A, B) {
return A || B;
}
function NOT(A) {
return !A;
}
console.log("A B | AND | OR | NOT A");
console.log("---------------------------");
[true, false].forEach(A => {
[true, false].forEach(B => {
console.log(`${A}<5} ${B}<5} | ${AND(A, B)}<4} | ${OR(A, B)}<3} | ${NOT(A)}`);
});
});
<IPython.core.display.Javascript object>
Popcorn Hack 3.5.1
def A():
return True
def B():
return True
if A():
print("A is true, so B must also be true:", B())
else:
print("A is false, we cannot conclude anything about B.")
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.
%%javascript
function A() {
return true;
}
function B() {
return true;
}
if (A()) {
console.log("A is true, so B must also be true:", B());
} else {
console.log("A is false, we cannot conclude anything about B.");
}
if (!B()) {
console.log("B is false, therefore A must also be false:", !A());
} else {
console.log("B is true, we cannot conclude anything about A.");
}
<IPython.core.display.Javascript object>