我收到以下提示:
create a function: BoolAdd(A,B) that performs binary addition on lists A and B (A and B have the same length N) of Boolean values and returns a list of two elements. The first element is an overflow, which means that it is returned with the value FALSE unless the addition does not fit into the same length list as A and B originally. The second element of the output list is a list of Boolean values that corresponds to the vector sum of A and B. Make sure that BOOL_ADD is defined so it works regardless of the value chosen for N.
我不确定如何执行二进制加法,然后将其转换为 boolean 值。我也不确定溢出何时会更改为 TRUE。在问题的前面,我们编写了以下 HalfAdder 函数:
def HalfAdder(A,B):
S = int((A and not B) or (not A and B))
C = int(A and B)
return (S, C)
和 FullAdder 函数:
def FullAdder(A,B,C):
AB = int((A and not B) or (not A and B))
S = int((C and not AB) or (not C and AB))
CAB = int(C and AB)
C1 = int((A and B) or (CAB))
return (S,C1)
其中任何一个都会被合并吗?
这是我到目前为止所做的,但还没有成功:
def BoolAdd(A,B):
L = []
overflow = False
for i in range (0,len(A)):
x = bin(A[i]+B[i])
x = bool(x)
L.append(x)
if (len(L) > len(A)):
overflow = True
return [overflow, L]
关于我做错了什么或者如何解决这个问题有什么想法吗?
最佳答案
你有一个半加法器,你需要构造一个full adder然后将输入列表中的每个元素的多个调用链接在一起,加上前面项目的进位。
链接是通过使用 ripple-carry 完成的技术,从前一组项目中获取“进位”输出并将其作为第三个输入。
关于python - 两个 boolean 值列表的二进制加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12924166/