[英]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.