[英]Summation without + operator in python
Need to get sum of x and y without +
operator.需要在没有
+
运算符的情况下获得 x 和 y 的总和。
I trid to sum two number using adder.If we xor x and y ( x ^ y
), we will get summation without carry.我尝试使用加法器对两个数字求和。如果我们对 x 和 y (
x ^ y
) 进行异或运算,我们将得到不带进位的求和。 From x & y
we can get carry.从
x & y
我们可以得到进位。 To add this carry in summation, call add function again.要将此进位加到总和中,请再次调用 add function。 but its not give answer.
但它没有给出答案。 where is the error in my code.
我的代码中的错误在哪里。
def add(a,b):
if a == 0:
return b
return add(a^b, a&b)
x = 10
y = 20
print(add(10, 20))
Error:错误:
File "main.py", line 4, in add
文件“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
You also have to shift the carries:您还必须转移进位:
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
This explains only why you end in an endless loop.这仅解释了为什么您会陷入无限循环。 Your proposed addition algorithm is flawed, see Thierry Lathuille 's answer for a correct addition as well.
您提出的加法算法存在缺陷,请参阅Thierry Lathuille的正确加法答案。
You forgot half of the base case:你忘记了一半的基本情况:
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))
prints印刷
30 # this only works for some numbers, you algo is not correct, try add(3,2)
Debugging:调试:
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
You missed two condition.你错过了两个条件。 If b == 0 then return a.
如果 b == 0 则返回 a。 Then also shift carry.
然后也转移进位。
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.