繁体   English   中英

python 中没有 + 运算符的求和

[英]Summation without + operator in python

需要在没有+运算符的情况下获得 x 和 y 的总和。

我尝试使用加法器对两个数字求和。如果我们对 x 和 y ( x ^ y ) 进行异或运算,我们将得到不带进位的求和。 x & y我们可以得到进位。 要将此进位加到总和中,请再次调用 add function。 但它没有给出答案。 我的代码中的错误在哪里。

def add(a,b):
    if a == 0:
        return b
    return add(a^b, a&b)

x = 10
y = 20
print(add(10, 20))

错误:

文件“main.py”,第 4 行,添加

return add(a^b, a&b) File "main.py", line 4, in add return add(a^b, a&b) File "main.py", line 4, in add return add(a^b, a&b) File "main.py", line 4, in add return add(a^b, a&b) File "main.py", line 4, in add return add(a^b, a&b) File "main.py", line 4, in add return add(a^b, a&b) File "main.py", line 4, in add return add(a^b, a&b) File "main.py", line 4, in add return add(a^b, a&b) File "main.py", line 4, in add return add(a^b, a&b) File "main.py", line 2, in add if a == 0: RuntimeError: maximum recursion depth exceeded in comparison

您还必须转移进位:

def add(a,b):
    if a == 0:
        return b
    if b == 0:
        return a
    return add(a^b, (a&b) << 1)

x = 3
y = 2
print(add(x, y))
# 5

仅解释了为什么您会陷入无限循环。 您提出的加法算法存在缺陷,请参阅Thierry Lathuille的正确加法答案。


你忘记了一半的基本情况:

def add(a,b):
    if a == 0 or b==0:   # if either one is zero
        return a or b         # return the non-zero one (or 0 if both are 0)
    return add(a^b, a&b)

x = 10
y = 20
print(add(10, 20))

印刷

30     # this only works for some numbers, you algo is not correct, try add(3,2)

调试:

def add(a,b):
    print(f"a  {bin(a):>10}")
    print(f"b  {bin(b):>10}")
    if a == 0 or b==0:
        return a or b
    return add(a^b, a&b)

a      0b1010
b     0b10100
-------------        # manually added the xor/and
xor     11110        # to show what happens:
and     00000        # b is 0       

a     0b11110
b         0b0        # now it terminates as b is 0

你错过了两个条件。 如果 b == 0 则返回 a。 然后也转移进位。

def add(a,b):
    if a == 0:
        return b
    if b == 0:
        return a
    return add(a^b, a&b << 1)

x = 10
y = 20
print(add(10, 20))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM