python - 两个 boolean 值列表的二进制加法

标签 python binary boolean

我收到以下提示:

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/

相关文章:

java - 将 boolean 值 True/False 与 JOptionPane.YES_NO_OPTION 一起使用

Java十进制到二进制转换错误

MySQL 十六进制二进制限制

ruby 为什么0 || 1 是 0

python - 在 Python 中,如何找到给定一周的第一个星期一的日期?

java - 将通过 php 套接字检索的字节转换为整数

python - 根据字典检查数据帧值(作为键,值元组)的矢量化方法?

python - 为什么 numba parallel=True 比 parallel=False 慢

使用Rascal分析和转换python源文件

python - 编译Python代码时出现unindent does not match any external indenting level错误