例如,如果您有a1 | a2 = 0011,a1 和 a2 的可能狀態是 =>result = [ (0000,0011) , (0001,0010) , (0001,0011) ]
和 a1 < a2。我們的數字不一定是 4 位,它們可以更多。
我的意思是,您有按位或的答案,并且您正在尋找 a2、a1(二進制)的所有可能狀態。
你能幫我如何在python中找到所有可能的狀態嗎?謝謝你。
uj5u.com熱心網友回復:
如果我理解正確,以下基于 itertools 的解決方案應該可以作業:
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')]
uj5u.com熱心網友回復:
程式與匹配結果的位數無關。十進制到二進制的方法。
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)
請注意,combinations回傳已排序的元組。
有點計算昂貴但用途廣泛:要獲得另一個按位運算的“輸入”,只需添加一個像這樣的新函式
def int2bin_str_AND(n1, n2, N=4):
return f"{int(bin(n1), 2) & int(bin(n2), 2):0{N}b}"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524667.html
標籤:Python数学
上一篇:10位數字和日期時間有什么關系
下一篇:重新計算縮放元素上的變換原點
