Popcorn Hack 1
Are these binary or not binary?
- 101010
- Yes, this string is binary because it consists of all zeros and ones.
- 12301
- No, this string is not binary because it has other numbers besides zeros and ones.
- 11001
- Yes, this string is binary because it contains only zeros and ones.
Popcorn Hack 2 (binary arithmetic)
Binary Addtion Rules:
A | B | Sum | Carry |
---|---|---|---|
0 | 0 | 0 | 0 |
0 | 1 | 1 | 0 |
1 | 0 | 1 | 0 |
1 | 1 | 0 | 1 |
1 | 1 | 1 | 1 (when there’s already a carry) |
- Add these:
- 101
- +110
- 1001
- 101
- Add these:
- 111
- +1001
- 1110
- 111
Binary Subtraction Rules:
A (minuend) | B (subtrahend) | Borrow | Result | New Borrow |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
1 | 0 | 0 | 1 | 0 |
1 | 1 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 (borrow) |
- Subtract these:
- 1101
- -1011
- 0010
Popcorn Hack 3 (True/False Logic):
What will be the result of this expression?
True or False and False
Answer: True
What will be the result of this expression?
not True and False
Answer: False
What will be the result of this expression?
True or False and not False
Answer: True
Homework Hack 1
def decimal_to_binary(n):
"""Converts a decimal number to binary (supports negatives)."""
if n == 0:
return "0"
is_negative = n < 0
n = abs(n)
binary = ""
while n > 0:
binary = str(n % 2) + binary
n //= 2
return "-" + binary if is_negative else binary
def binary_to_decimal(binary_str):
"""Converts a binary string to a decimal number (supports negatives)."""
if not binary_str:
raise ValueError("Input cannot be empty")
is_negative = binary_str.startswith("-")
binary_str = binary_str.lstrip("-")
decimal = 0
for i, digit in enumerate(reversed(binary_str)):
if digit not in "01":
raise ValueError("Invalid binary string")
decimal += int(digit) * (2 ** i)
return -decimal if is_negative else decimal
# Test cases
test_numbers = [0, 1, -1, 5, -10, 255, -128]
print("Decimal to Binary:")
for num in test_numbers:
print(f"{num} -> {decimal_to_binary(num)}")
print("\nBinary to Decimal:")
for num in test_numbers:
binary = decimal_to_binary(num)
print(f"{binary} -> {binary_to_decimal(binary)}")
Decimal to Binary:
0 -> 0
1 -> 1
-1 -> -1
5 -> 101
-10 -> -1010
255 -> 11111111
-128 -> -10000000
Binary to Decimal:
0 -> 0
1 -> 1
-1 -> -1
101 -> 5
-1010 -> -10
11111111 -> 255
-10000000 -> -128
Homework Hack 2
import time
difficulty = input("Enter difficulty (easy, medium, hard): ").lower().strip()
while difficulty != "easy" or difficulty != "medium" or difficulty != "hard":
print("Please enter a valid difficulty level.")
difficulty = input("Enter difficulty (easy, medium, hard): ").lower().strip()
time.sleep(0.5)
print("Difficulty set to:", difficulty)