python中的多项式函数

时间:2016-02-02 16:59:10

标签: python polynomials

我是编写Python代码的新手。我必须像这样表示多项式,

4x^230+7x^96+1

testP = [[4,512],[7,256],[1,0]]

def printPoly2(P):
    for i in range(len(P)):
        if P[i] != 0:
            print("%s x^%s + "%(P[i], i)),
            print

printPoly2(testP)

但我的回答不正确。我需要帮助。

4 个答案:

答案 0 :(得分:0)

您的问题出在print语句中。写下:

print("%s x^%s + "%(P[i], i))

您实际上正在打印整个元组。例如,P[0]等于整个列表[4, 512]。因此,在直接打印P[i]时,您只需打印整个子列表。

相反,您希望打印子列表中的每个元素。

print("%s x^%s" % (P[i][0], P[i][1]))


此外,您的解决方案将在单独的行中打印答案的每个部分。要解决此问题,您有几个选项,但这里有一个不依赖于您拥有的python版本的选项。基本上,您创建一个表示结果的字符串,并在循环中继续构建它。然后在函数的最后,打印该字符串。

result = '' # initialize an empty string before your loop

然后在循环中用以下内容替换打印调用:

result = "%s + %s x^%s" % (result, P[i][0], P[i][1]

在函数的最后,您可以打印字符串。

print (result)

答案 1 :(得分:0)

我(希望)用一些pythonic魔法改进你的代码。现在它是一个元组列表,并使用自动元组展开。

testP = [(4, 230), (7, 96), (1, 0)]

def printPoly2(P):
    for i, e in P:
        if e != 0:
            print("{} x^{} + ".format(i, e))

printPoly2(testP)

打印

4 x^230 + 
7 x^96 + 

答案 2 :(得分:0)

再过5分钟......你走了

testP = [(4, 230), (7, 96), (1, 0)]

def printPoly2(polynom):
    parts = []
    for i, e in polynom:
        parts.append(_format_polynome(i,e))

    print " + ".join(parts)

def _format_polynome(i, e):
    if e == 0:
        return "{}".format(i)
    else:
        return "{} x^{}".format(i, e)

printPoly2(testP)

答案 3 :(得分:0)

this is how I would write this code in something I think is a more pythonic way of writting it:

def poly2(P):
    result = []
    for item in P:
        n, e = item
        if e == 0:
            result.append("1")
        else:
            result.append("{}x^{}".format(n, e))
    return " + ".join(result)

# 4x^230 + 7x^96 + 1
testP = [(4,230), (7,96), (1,0)]
print poly2(testP)

note that its more flexible to return a string representation than to print it directly from the function.

相关问题