math / modules /subtraction_bases.py
Sina Media Lab
Add application file 4
32f2e18
raw
history blame
1.33 kB
import random
title = "Subtraction in Base 2 Using 2's Complement"
description = "This module teaches subtraction in binary using the 2's complement method, which allows subtraction to be performed as an addition operation."
def generate_question():
num1 = random.randint(1, 7)
num2 = random.randint(1, 7)
result = num1 - num2
bit_length = 4
if result >= 0:
binary_result = bin(result)[2:].zfill(bit_length)
else:
binary_result = bin((1 << bit_length) + result)[2:]
question = f"Subtract {num2} from {num1} in base 2 using 2's complement method."
correct_answer = binary_result
options = [correct_answer]
# Generate incorrect options
while len(options) < 5:
fake_option = bin(random.randint(-7, 7) & 0xF)[2:]
if fake_option not in options:
options.append(fake_option)
random.shuffle(options)
explanation = (
f"The result of subtracting {num2} from {num1} in base 2 using 2's complement is {binary_result}."
"\n\n**Step-by-step solution:**\n"
"1. Find the 2's complement of the subtracted number.\n"
"2. Add it to the first number.\n"
"3. If there's a carry, discard it. The result is the binary difference."
)
return question, options, correct_answer, explanation