-3
def print_poly(p):

    """
      >>> print_poly([4, 3, 2])
      4x^2 + 3x + 2
      >>> print_poly([6, 0, 5])
      6x^2 + 5
      >>> print_poly([7, 0, -3, 5])
      7x^3 - 3x + 5
      >>> print_poly([1, -1, 0, 0, -3, 2])
      x^5 - x^4 - 3x + 2
    """

    printable = ''

    for i in range(len(p) -1, -1, -1):
        poly += ('p[i]' + 'x^' + str(i))
    for item in printable:
        if 0 in item:
            item *= 0
    printable += poly[0]
    for item in poly[1:]:
        printable += item
    print(printable)

无论我尝试多少次,我都无法让所有的文档测试都通过。

4

1 回答 1

0

我真的不知道你在问什么,但无论如何我都会尝试回答。

你想在 python 中定义一个函数(你应该将它添加到你的标签中),以便 print_poly([coef0,coef1,...,coefn]) 产生一个多项式:

coef0*x^(n)+coef1*x^(n-1)+...+coefn

尝试这个:

def print_poly(list):
    polynomial = ''
    order = len(list)-1
    for coef in list:
        if coef is not 0 and order is 1:
            term = str(coef) + 'x'
            polynomial += term
        elif coef is not 0 and order is 0:
            term = str(coef)
            polynomial += term
        elif coef is not 0 and order is not 0 and order is not 1:
            term = str(coef) + 'x^' + str(order)
            polynomial += term
        elif coef is 0:
            pass

        if order is not 0 and coef is not 0:
            polynomial += ' + '
        order += -1
    print(polynomial)

有你的答案,但老实说,你应该尝试自己检查 python 函数定义、布尔运算符和数学运算符,因为看起来你没有很好地掌握它们。

布尔运算符 - https://docs.python.org/3.1/library/stdtypes.html 算术 - http://en.wikibooks.org/wiki/Python_Programming/Operators Functions - http://en.wikibooks.org/wiki /非程序员的_Tutorial_for_Python_3/Defining_Functions

如果你有承诺:Learn Python The Hard Way ( http://learnpythonthehardway.org/ )

于 2014-07-28T20:39:28.083 回答