Python-Why aren't my elif statements not getting evaluated in this recursive multiplication which takes into account negative numbers

和自甴很熟 提交于 2021-01-29 11:32:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!