File size: 2,314 Bytes
5f6edac
 
62b8133
 
c9ca893
 
7172720
d924141
7172720
5f6edac
 
 
 
 
 
 
 
 
 
 
 
 
 
c9ca893
5f6edac
 
 
 
 
 
 
 
c9ca893
5f6edac
 
 
 
c9ca893
5f6edac
c9ca893
 
5f6edac
 
c9ca893
5f6edac
 
 
 
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
56
57
58
# modules/number_system/twos_complement.py

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():
    bit_lengths = [4, 5, 6, 7, 8]
    num_bits = random.choice(bit_lengths)
    
    def generate_binary_number(length):
        return ''.join(random.choice('01') for _ in range(length))
    
    number = generate_binary_number(num_bits)
    
    def calculate_twos_complement(binary_str, length):
        if binary_str == '0' * length:
            return binary_str  # 2's complement of 0 is still 0
        # Invert the bits (1's complement)
        ones_complement = ''.join('1' if bit == '0' else '0' for bit in binary_str)
        # Add 1 to the 1's complement
        twos_complement = bin(int(ones_complement, 2) + 1)[2:]
        # Ensure the result is truncated or zero-padded to fit the specified bit length
        return twos_complement.zfill(length)[-length:]
    
    correct_answer = calculate_twos_complement(number, num_bits)
    
    options = {correct_answer}
    
    # Generate incorrect answers
    while len(options) < 4:
        invalid_number = generate_binary_number(num_bits)
        invalid_twos_complement = calculate_twos_complement(invalid_number, num_bits)
        if invalid_twos_complement != correct_answer:
            options.add(invalid_twos_complement)
    
    options = list(options)
    random.shuffle(options)
    
    question = f"What is the 2's complement of the {num_bits}-bit binary number {number}?"
    explanation = f"The 2's complement of the {num_bits}-bit binary number {number} is {correct_answer}."
    step_by_step_solution = [
        f"Step 1: Invert the bits (1's complement) of the binary number {number}.",
        f"Step 2: Add 1 to the result to get the 2's complement.",
        f"Step 3: Ensure the result is a {num_bits}-bit binary number by truncating or zero-padding if necessary.",
        f"Step 4: The 2's complement of the {num_bits}-bit binary number {number} is {correct_answer}."
    ]
    
    return {
        "question": question,
        "options": options,
        "correct_answer": correct_answer,
        "explanation": explanation,
        "step_by_step_solution": step_by_step_solution
    }