math / modules /twos_complement.py
Sina Media Lab
Updates
c9ca893
raw
history blame
1.4 kB
# modules/twos_complement.py
title = "2's Complement Questions"
description = "This module explains the 2's complement method for representing negative numbers."
def generate_question():
import random
number = ''.join(random.choice('01') for _ in range(8))
def calculate_twos_complement(number):
n = len(number)
ones_complement = ''.join('1' if bit == '0' else '0' for bit in number)
twos_complement = bin(int(ones_complement, 2) + 1)[2:]
return twos_complement.zfill(n)
correct_answer = calculate_twos_complement(number)
options = [correct_answer]
# Generate incorrect answers
while len(options) < 4:
invalid_number = ''.join(random.choice('01') for _ in range(8))
if invalid_number != correct_answer:
options.append(invalid_number)
random.shuffle(options)
question = f"What is the 2's complement of the binary number {number}?"
explanation = f"The 2's complement of {number} is {correct_answer}."
step_by_step_solution = [
"Step 1: Find the 1's complement by flipping all bits.",
"Step 2: Add 1 to the 1's complement to get the 2's complement."
]
return {
"question": question,
"options": options,
"correct_answer": correct_answer,
"explanation": explanation,
"step_by_step_solution": step_by_step_solution
}