-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)

何度やっても、すべての doctest に合格することはできません。

4

1 に答える 1

0

何を聞かれているのかよくわかりませんが、とりあえず答えてみます。

print_poly([coef0,coef1,...,coefn]) が多項式になるように定義された関数を Python で使用する必要があります (タグに追加する必要があります)。

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

コミットメントがある場合: Learn Python The Hard Way ( http://learnpythonthehardway.org/ )

于 2014-07-28T20:39:28.083 に答える