Tri 3 College Board Quiz Blog

Pre-Quiz Prep (Popcorn Hacks)

Cause of Overflow Error:

# python overflow example
# as a popcorn hack (binary challenge), describe an overflow in 8 binary digits
# Add 1 to 11111111 (255)
# Subtract 1 from 00000000 (0)
# Try overflow and underflow here: https://nighthawkcoders.github.io/teacher_portfolio/c4.4/2023/09/14/javascript-binary-U2-1.html

import sys

# Maximum float
max_float = sys.float_info.max
print(f"Max float: {max_float}")

# Attempt to overflow float
overflow_float = max_float * 2
print(f"Overflow float to infinity: {overflow_float}") 
Max float: 1.7976931348623157e+308
Overflow float to infinity: inf

The maximum representative value of 8 bit binary is 11111111 (255). When we add 1 to it, it would be 100000000 but only 8 bits can be represented so the 9th bit gets discarded, resulting in an overflow error. Similarly, when subtracting 1 from the minimum representable value in 8-bit binary (00000000), the result would be -1. This value is also outside the representable range of 8 bits, resulting in an underflow error.

Inputs to Logic circuit:

# represent gates and circuits
# as a popcorn hack (coding challenge), create multiple new circuits and gates
# NOT, NAND, NOR, XOR, XNOR
# Create a hypothetical circuit, such as burglar alarm, decision tree for autonomous car, etc.

# OR gate
def OR_gate(A, B):
    return A or B

# AND gate
def AND_gate(A, B):
    return A and B

# NOT gate
def NOT_gate(A):
    return not A

# NAND gate
def NAND_gate(A, B):
    return not (A and B)

# NOR gate
def NOR_gate(A, B):
    return not (A or B)

# XOR gate
def XOR_gate(A, B):
    return (A or B) and not (A and B)

# XNOR gate
def XNOR_gate(A, B):
    return (A and B) or (not A and not B)

# Hypothetical circuit for a burglar alarm system
# A represents motion sensor, B represents door sensor
# The alarm should go off if either motion sensor or door sensor is triggered
def burglar_alarm(A, B):
    return OR_gate(A, B)

# Theoritical circuit representing a Car starting
# A and B could be security checks, such as key being inserted or a fob being present
# C and D could be operational checks, such as a start button being pressed and safety belt being fastened
# The enclosing AND gate ensures car only operates when both security and operational checks are met
def circuit(A, B, C, D):
    return AND_gate(OR_gate(A, B), AND_gate(C, D))

# Print truth table for circuit
print('A', 'B', 'C', 'D', "-->", 'Output')
# nesting of loops for both the True, False combination of A, B, C, D 
# this algorithm is 2 ^ 4 = 16, thus producing all 16 combinations 
# each combination terminates with the output of the circuit
for A in [False, True]:
    for B in [False, True]:
        for C in [False, True]:
            for D in [False, True]:
                print(A, B, C, D, "-->", circuit(A, B, C, D))
                
# Print truth table for circuit
print('A', 'B', 'C', 'D', "-->", 'Output')
for A in [False, True]:
    for B in [False, True]:
        for C in [False, True]:
            for D in [False, True]:
                print(A, B, C, D, "-->", burglar_alarm(A, B))

Added NOT, NAND, NOR, XOR, and XNOR circuits and hypothetical circuit for the burgalar alarm

Color represented by binary triplet

# Convert binary RGB triplet to decimal
# as a hack (binary challenge), make the rgb standard colors
# as a 2nd hack, make your favorite color pattern 

import matplotlib.pyplot as plt
import matplotlib.patches as patches

# Function to convert binary to decimal
def binary_to_decimal(binary):
    return int(binary, 2)

def plot_colors(rgb_triplets):
    # Create a figure with one subplot per RGB triplet
    fig, axs = plt.subplots(1, len(rgb_triplets), figsize=(2 * len(rgb_triplets), 2))
    
    # Ensure axs is always a list
    axs = axs if len(rgb_triplets) > 1 else [axs]

    for ax, (red_binary, green_binary, blue_binary) in zip(axs, rgb_triplets):
        # Convert to binary strings to decimal
        red_decimal = binary_to_decimal(red_binary)
        green_decimal = binary_to_decimal(green_binary)
        blue_decimal = binary_to_decimal(blue_binary)

        # Normalize number to [0, 1] range, as it is expected by matplotlib 
        red, green, blue = red_decimal/255, green_decimal/255, blue_decimal/255

        # Define a rectangle patch with the binary RGB triplet color and a black border
        rect = patches.Rectangle((0, 0), 1, 1, facecolor=(red, green, blue), edgecolor='black', linewidth=2)
        
        # Add the rectangle to the plot which shows the color 
        ax.add_patch(rect)

        # Remove axis information, we just want to see the color
        ax.axis('off')

        # Print the binary and decimal values
        print("binary:", red_binary, green_binary, blue_binary)    
        print("decimal", red_decimal, green_decimal, blue_decimal)
        print("proportion", red, green, blue)

    # Show the colors
    plt.show()

# Test the function with a list of RGB triplets
rgb_triplet = [('00000000', '00000000', '11110000')] # College Board example
plot_colors(rgb_triplet)

rgb_primary = [('11111111', '00000000', '00000000'), 
                ('11111111', '11111111', '00000000'),
                ('00000000', '00000000', '00000000')]
plot_colors(rgb_primary)
binary: 00000000 00000000 11110000
decimal 0 0 240
proportion 0.0 0.0 0.9411764705882353

png

binary: 11111111 00000000 00000000
decimal 255 0 0
proportion 1.0 0.0 0.0
binary: 11111111 11111111 00000000
decimal 255 255 0
proportion 1.0 1.0 0.0
binary: 00000000 00000000 00000000
decimal 0 0 0
proportion 0.0 0.0 0.0

png

Hack: make your favorite color and favorite set of colors

Compare execution times

import time

# Fibonacci function
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

# Measure the time taken to calculate Fibonacci sequence
def measure_fibonacci_time(n):
    start_time = time.time()  # Start timer
    result = fibonacci(n)  # Calculate Fibonacci sequence
    end_time = time.time()  # End timer
    elapsed_time = end_time - start_time
    print(f"Fibonacci({n}) took {elapsed_time:.6f} seconds")

# Test the functions
small_number = 20
large_number = 350

print("Calculating Fibonacci sequence for a small number:")
measure_fibonacci_time(small_number)

print("\nCalculating Fibonacci sequence for a large number:")
measure_fibonacci_time(large_number)

Error with multiplication using repeated addition

def multiply(x, y):
    if y == 0 or x == 0:  # Multiplying by 0 always results in 0
        return 0
    
    sign = 1 # Determine the sign of the result
    if x < 0:
        sign *= -1
        x = -x
    if y < 0:
        sign *= -1
        y = -y

    result = 0
    for _ in range(y):
        result += x
    
    return result * sign

# Test cases
print(multiply(2, 5))    # Expected output: 10
print(multiply(2, -5))   # Expected output: -10
print(multiply(-2, 5))   # Expected output: -10
print(multiply(-2, -5))  # Expected output: 10

10
-10
-10
10

Hack: change the multiply function so that it works with negative numbers

### Call to concat and substring

# Incorrect Answer D
# as a popcorn hack (binary challenge), create string and concatenation options for A, B, C
 
animal = "jackrabbit"[0:4]  # Substring("jackrabbit", 1, 4)
animal += "a"  # Concat(animal, "a")
animal = animal + "antelope"[4:8]  # Concat(Substring("antelope", 5, 4), animal)
print(animal)  # Outputs: lopejacka
jackalope

Hack: make Jackalope

Quiz Score

59/70

Quiz Corrections

  • Question 23 - True Statement About the Internet

Answer B is correct . I think I got this wrong because in the answer I chose, it said that the Internet uses propietary protocalls but I didn’t know that propietary was referring to ownership. The Internet was designed to be scalable, using open protocols to easily connect additional computing devices to the network.

  • Question 25 - Result of Iteration Statements

Answer D is correct because the procedure initially sets result to 1 and j to 2. In the REPEAT UNTIL loop, result is first assigned the sum of result and j, or 1 + 2. The value of j is then increased to 3. In each subsequent iteration of the loop, result is increased by each successive value of j (3, 4, 5, etc.) until j exceeds n. Therefore, the procedure returns the sum of the integers from 1 to n.

  • Question 26 - Algorithm not suited for parallel computing

I got this one wrong because I forgot what parallel computing was. After searching it up, I know that answer A is correct because the efficiency of a parallel computing solution is limited by the sequential portion of the solution. Therefore, the solution is completely sequential and does not benefit from parallel computing.

  • Question 37 - Which is not a possible value displayed

I got this one wrong because I looked over the IF ELSE statement. Answer C is correct. Carrot can only be displayed when the expression (n > 10) is false and the expression (n > 100) is true. If n is not greater than 10, it cannot be greater than 100, and so “carrot” can never be displayed.

  • Question 38 - Situation where simulation is unsuitable

I got this one wrong because I wasn’t aware of when a simulation is most beneficial. Answer D is correct because simulations are most useful when real-world events are impractical. A simulation is unlikely to be appropriate if continuous real-world data is needed.

  • Question 42 - Iterate over integerList

I got this one wrong because I didn’t know what the expression (item MOD 2) really did. Answer A is correct because the expression (item MOD 2) evaluates to 1 for odd values and evaluates to 0 for even values. As a result, the code segment adds 1 to result for each odd value in integerList.

  • Question 52 - Binary Search on a list of 128 items

I got this one wrong because I forgot how a binary search element worked. Answer B is correct. The binary search algorithm starts at the middle of the list and repeatedly eliminates half the elements until the desired value is found or all elements have been eliminated. For a list with 128 elements, the list will be cut in half a maximum of 7 times. 128,64,32,16,8,4,2,

  • Question 55 - Move element from end of list to beginning

Answer C is correct. This code segment assigns the value of the last element of the list to the variable temp, then removes the last element of the list, then inserts temp as the first element of the list.

  • Question 67 - Behavior of blue orange purple spinner

Answer A was correct but answer C was not. The Correct answer was A and D. I didn’t include the fact that if the first spin isn’t 1, then it needs to spin again to a value in between 1 and 2 inclusive.

  • Question 68 - Error in remove duplicates code segment

I think I just read over the NOT part of the question and got both of them wrong. Answers A and C are correct. Answer A is correct because as it iterates over from right to left, it removes the sixth, forth, and second element resulting in [10,20,10] which still contains duplicates. Answer D is correct because as it itereates it won’t remove any adjacent elements even though 40 appears twice.

  • Question 70 - Remove nth character from oldStr

Answer C was correct but Answer A was also correct, not B. Answer A was correct because the code segment assigns the characters to the left of position n to the variable left and the characters to the right of position n to the variable right. It then concatenates left and right and assigns the result to newStr.