Find the possible states to make the result of the Bitwise OR answer

Question:

For example if you have a1 | a2 = 0011 so the possible states for a1 and a2 are => result = [ (0000,0011) , (0001,0010) , (0001,0011) ]
and a1 < a2.
Our numbers are not necessarily 4-bit, they can be more.

I mean, you have the answer of Bitwise OR and you are looking for all possible states for a2, a1 (in binary).

Could you help me how to find all possible states in python? Thank you.

Asked By: mostafa

||

Answers:

If I understand you right, the following itertools-based solution should work:

from itertools import product

def or_factors(bits):
    bit_pairs = [[('0','0')] if i == '0' else [('0','1'),('1','0'),('1','1')] for i in bits]
    num_pairs = product(*bit_pairs)
    factors = []
    for pair in num_pairs:
        a = ''
        b = ''
        for s,t in pair:
            a += s
            b += t
        if a < b: factors.append((a,b))
    return factors

print(or_factors('0011'))
#[('0000', '0011'), ('0001', '0010'), ('0001', '0011'), ('0010', '0011')]
Answered By: John Coleman

The program is independent from the amount of bits of the matching result. A decimal to binary approach.

from itertools import combinations

def int2bin_str(n, N=4):
    return f"{int(bin(n), 2):0{N}b}"

def int2bin_str_OR(n1, n2, N=4):
    return f"{int(bin(n1), 2) | int(bin(n2), 2):0{N}b}"

res = "0011"

combs = []
N = len(res)
max_b = 2**N - 1 # maximal binary out of N-bits

for n1, n2 in combinations(range(max_b+1), r=2):
    if int2bin_str_OR(n1, n2, N=N) == res:
        combs.append((int2bin_str(n1, N=N), int2bin_str(n2, N=N)))

print(combs)

Notice that combinations returns already ordered tuples.


A bit computational expensive but versatile: to get the "inputs" of another bitwise operation just add a new function like this

def int2bin_str_AND(n1, n2, N=4):
    return f"{int(bin(n1), 2) & int(bin(n2), 2):0{N}b}"
Answered By: cards
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.