File size: 1,140 Bytes
d924141
 
 
984a89c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import random

def generate_question():
    binary_number = bin(random.randint(1, 15))[2:].zfill(4)

    def twos_complement(binary_str):
        n = len(binary_str)
        ones_complement = ''.join('1' if bit == '0' else '0' for bit in binary_str)
        twos_complement_result = bin(int(ones_complement, 2) + 1)[2:].zfill(n)
        return twos_complement_result[-n:]

    correct_answer = twos_complement(binary_number)

    steps = [
        f"Start with the binary number: {binary_number}.",
        f"Find the 1's complement by flipping each bit: {''.join('1' if bit == '0' else '0' for bit in binary_number)}.",
        f"Add 1 to the 1's complement to get the 2's complement: {correct_answer}.",
    ]

    question_data = {
        "question": f"What is the 2's complement of the binary number {binary_number}?",
        "options": [correct_answer] + [bin(random.randint(1, 15))[2:].zfill(4) for _ in range(3)],
        "correct_answer": correct_answer,
        "explanation": f"The 2's complement of the binary number {binary_number} is {correct_answer}.",
        "step_by_step_solution": steps
    }

    return question_data