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

No matter how many times I try, I just can't get all the doctests to pass.

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
  • As a first step, can you get it to work for inputs of a specify size? For instance, get it working assuming that `p` is a list of 3 coefficients, then try to generalize from there. This will help determine if your problem is in iterating over a list of arbitrary size, or if you have a problem constructing the correct string. Also, does your function produce *any* output, or does it just produce output that does not conform to the expected output? – chepner Jul 28 '14 at 16:53
  • poly isnt initialized and you try use the operator += on it.. When you fix that, there will be incorrect output, but at least there will be output – Emile Vrijdags Jul 28 '14 at 16:58
  • This looks like it was written in one go. What is `poly`? `'p[i]'` doesn't do what you think it does. Print EVERYTHING along the way – Ben Jul 28 '14 at 16:58

1 Answers1

0

I don't really know what you're asking, but I'm going to try to answer it anyway.

You want to have a function in python (you should add that to your tags) that is defined so that print_poly([coef0,coef1,...,coefn]) results in a polynomial:

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

try this:

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)

There is your answer, but honestly you should try to go over python function definitions, boolean operators, and math operators on your own as it looks like you don't have a good grasp of them.

Boolean Operators - https://docs.python.org/3.1/library/stdtypes.html Arithmetic - http://en.wikibooks.org/wiki/Python_Programming/Operators Functions - http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_3/Defining_Functions

And if you have the commitment: Learn Python The Hard Way (http://learnpythonthehardway.org/)

cdipaolo
  • 229
  • 1
  • 2
  • 10