我有两个二进制整数,x0和x1是8位(所以它们从0到255).关于这些数字,这句话总是正确的:x0& x1 == 0.这是一个例子:
bx0 = 100 # represented as 01100100 in binary
bx1 = 129 # represented as 10000001 in binary
所以我需要对这些数字进行以下操作.首先,将这些二进制表示解释为ternary(base-3)数字,如下所示:
tx0 = ternary(bx0) # becomes 981 represented as 01100100 in ternary
tx1 = ternary(bx1) # becomes 2188 represented as 10000001 in ternary
然后,将tx1的三元表示中的所有1交换为2:
tx1_swap = swap(tx1) # becomes 4376,represented as 20000002 in ternary
然后在它们上使用三元版本的OR来获得最终的组合数字:
result = ternary_or(tx0,tx1_swap) # becomes 5357,represented as 21100102 in ternary
我不需要在任何时候保存三元表示,我只需要结果,例如result = 5357.当然,我可以通过将数字转换为二进制,转换为三元等来编码.但是我需要这个操作很快,因为我在我的代码中这么做了很多次.在python中实现这个的快速方法是什么?
最佳答案
重新解释像我这样的假人:
原文链接:https://www.f2er.com/python/438932.html在三元组中“编码”两个二进制互斥数字(w& b == 0)的直接方法是:
white_black_empty = lambda w,b: int(format(b,'b'),base=3) + \
int(format(w,'b').replace('1','2'),base=3)
以下是所有可能的2位变体:
white_black_empty(0b00,0b00) == 0
white_black_empty(0b00,0b01) == 1
white_black_empty(0b01,0b00) == 2
white_black_empty(0b00,0b10) == 3
white_black_empty(0b00,0b11) == 4
white_black_empty(0b01,0b10) == 5
white_black_empty(0b10,0b00) == 6
white_black_empty(0b10,0b01) == 7
white_black_empty(0b11,0b00) == 8
通过观察int(格式(w,’b’).replace(‘1′,’2′),base = 3)实际上等于int的两倍(格式(w,’b’),base = 3) (例如,20220023 == 10110013 * 2),我们得到了@Mark Dickinson在上述评论中发布的解决方案:
white_black_empty = lambda w,base=3)*2