File size: 1,990 Bytes
62b8133
 
c9ca893
 
 
d924141
 
c9ca893
984a89c
c9ca893
62b8133
c9ca893
62b8133
 
c9ca893
62b8133
 
 
984a89c
62b8133
c9ca893
984a89c
c9ca893
 
 
 
 
 
 
 
 
62b8133
 
 
 
 
 
c9ca893
62b8133
 
 
 
 
c9ca893
 
62b8133
 
c9ca893
 
 
984a89c
c9ca893
 
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import random
import sympy as sp

title = "2's Complement Questions"
description = "This module explains the 2's complement method for representing negative numbers."

def generate_question():
    number = ''.join(random.choice('01') for _ in range(8))

    def calculate_twos_complement(number):
        # Calculate 1's complement
        ones_complement = ''.join('1' if bit == '0' else '0' for bit in number)
        
        # Calculate 2's complement
        twos_complement = bin(int(ones_complement, 2) + 1)[2:]
        twos_complement = twos_complement.zfill(len(number))
        
        return ones_complement, twos_complement

    ones_complement, 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}?"
    
    # Generate a step-by-step solution using SymPy
    num_expr = sp.sympify(f'0b{number}')
    ones_expr = sp.sympify(f'0b{ones_complement}')
    twos_expr = ones_expr + 1

    step_by_step_solution = [
        f"Step 1: Start with the original binary number: {number}",
        f"Step 2: Find the 1's complement by flipping all bits: {ones_complement}",
        f"Step 3: Add 1 to the 1's complement:",
        f"        {ones_complement} + 1 = {bin(twos_expr)[2:].zfill(len(number))}",
        f"Step 4: The 2's complement of {number} is {correct_answer}."
    ]
    
    explanation = f"The 2's complement of {number} is {correct_answer}. It is calculated by inverting the bits and adding 1."

    return {
        "question": question,
        "options": options,
        "correct_answer": correct_answer,
        "explanation": explanation,
        "step_by_step_solution": step_by_step_solution
    }