PYTHON 3.0负数不作为输入

时间:2015-09-23 04:14:53

标签: python python-3.x math negative-number

我正在尝试制作一个保理程序,但它似乎不适用于负数a-,b-和c-输入。

from fractions import gcd
factor = -1
opp = 0
number = 1
success = 0
a = int(input("a-value: "))
b = int(input("b-value: "))
c = int(input("c-value: "))
factors = []
d = 0
e = 0
while number <= abs(a*c):
#Checking for multiples
    if abs(a*c) % number == 0:
        factor += 1
        factors.append(number)
    number += 1
while (factor-opp) >= 0:
#Checking for actual factors
    d = int(factors[factor])
    e = int(factors[opp])
    if (abs(d+e) or abs(d-e)) == abs(b):
        success += 1
        break
    else:
        factor -= 1
        opp += 1

if success > 0:

    if (d+e) == b:
        e = e
    elif (d-e) == b:
        e -= 2*e
    elif (e-d) == b:
        d -= 2*d
    elif (-d-e) == b:
        d -= 2*d
        e -= 2*e
    #Figuring out the equation
    if d % a == 0:
        d /= a
        f = 1
    else:
        f = a/gcd(d,a)
        d /= gcd(d,a)

    if e % a == 0:
        e /= a
        g = 1
    else:
        g = a/gcd(e,a)
        e /= gcd(e,a)
    #Displaying the answer
    if d >= 0:
        d = str("+" + str(int(d)))
        if e >= 0:
            e = str("+" + str(int(e)))
        elif e < 0:
            e = str(int(e))
    else:
        d = str(int(d))
        if e >= 0:
            e = str("+" + str(int(e)))
        elif e < 0:
            e = str(int(e))
    if f == 1:
        if g == 1:
            print ("(x" + d + ")(x" + e + ")")
        else:
            g = str(int(g))
            print ("(x" + d + ")(" + g + "x" + e + ")")
    elif g == 1:
        f = str(int(f))
        print ("(" + f + "x" + d + ")(x" + e + ")")
    else:
        f = str(int(f))
        g = str(int(g))
        print ("(" + f + "x" + d + ")(" + g + "x" + e + ")")
else:
    print("This equation cannot be factored into integers.")

更具体地说,我想这个问题就在这个街区的某个地方。我用打印语句对它进行了测试:

while (factor-opp) >= 0:
#Checking for actual factors
    d = int(factors[factor])
    e = int(factors[opp])
    if (abs(d+e) or abs(d-e)) == abs(b):
        success += 1
        break
    else:
        factor -= 1
        opp += 1

我到处搜索:我的编程教科书,关于输入底片的在线搜索,一切。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

好的,我可以为一个简单的测试用例重现您的问题,例如 - a=1 , b=0, c=-4

问题在于 -

if (abs(d+e) or abs(d-e)) == abs(b):

这不会检查abs(b)是否等于abs(d+e)abs(d-e),而是首先评估(abs(d+e) or abs(d-e))的结果,这会返回第一个非零结果,然后将其与abs(b)进行比较,因此对于负数,这不会正确评估结果。将该条件更改为 -

if abs(d+e) == abs(b) or abs(d-e) == abs(b):

或者你也可以使用一套 -

if abs(b) in {abs(d+e), abs(d-e)}:           #Though I doubt if using set would give any performance improvement because of the overhead of creating a set.

更改后的演示 -

a-value: 1
b-value: 0
c-value: -4
(x+2)(x-2)

a-value: 1
b-value: -1
c-value: -6
(x-3)(x+2)

还有一件事,有些事情你没有考虑过,在a=-1 , b=-4 , c=-4时,结果应该是-(x+2)(x+2),但当前的程序会产生(x+2)(x+2)