问题
Hi I have looked up a few recursive multiplication of 2 numbers in python, but none of them take into account the possibility of negative numbers or if they do they don't explain the entire steps.
I have coded the following the program but I am getting an error, can someone please let me know what is wrong with it?
def mult(a,b):
if a==0 | b==0:
return 0
elif a==1:
return b
elif a > 0 & b >0:
return b + mult(a-1,b)
elif a < 0 & b > 0:
return - b + mult(a+1,b))
elif a > 0 & b < 0:
return - b + mult(a-1, b))
else:
return -b + mult(a+1, b)
print(mult(-4,5))
回答1:
|
and &
are bitwise operators, not logical operators, and their (relatively) high precedence means that a > 0 & b >0
is parsed as a > (0 & b) > 0
, which is not what you want. Use or
and and
instead.
回答2:
You have some python syntax errors and some sign problems. This works for mult(-4,5) and mult(5,-4).
def mult(a,b):
if a == 0 or b == 0:
return 0
elif a == 1:
return b
elif b == 1:
return a
elif a >0 and b > 0:
return b + mult(a-1,b)
elif a < 0 and b > 0:
return -b+mult(a+1,b)
elif a > 0 and b < 0:
return b+mult(a-1,b)
else:
return b + mult(a+1,b)
回答3:
In your elif statement, you're using a bitwise "and" operator rather than the logical and operator. Everywhere that you have "&" replace it with "and"
来源:https://stackoverflow.com/questions/51386324/python-why-arent-my-elif-statements-not-getting-evaluated-in-this-recursive-mul