编写一个获取表示多项式的列表的函数

时间:2014-07-28 16:50:17

标签: python polynomials

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)

无论我尝试多少次,我都无法让所有的医生通过。

1 个答案:

答案 0 :(得分: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 函数 - http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_3 / Defining_Functions

如果你有承诺: 学习Python艰难的方式(http://learnpythonthehardway.org/