3

I have a problem with this task. I have to print a polynomial, which is an input from a user. (I have problem with this too because it can be polynomial of any degree and I'm not so sure how to print it). The second part of the task is to find a derivative of this polynomial. I tried to this by asking a user for a degree of this polynomial and the coefficients and then creating a list but I don't think its a good way so please help me!

I have something like this:

n = int(input("What is a degree of poly: "))
lista = []
for i in range (n+1):
    a = int(input("What are the coefficients "))
    lista.append(a)

lista1 = []
b = n
d = 0
for k in range (n+1):
    c = int(lista[d])*int(b)
    lista1.append(c)
    b = b - 1
    d = d + 1

print(lista1)
Sanjit Sarda
  • 381
  • 1
  • 4
  • 13
  • 4
    You might take a look at the sympy module. It has means for representing polynomials, differentiating them, and for displaying them via latex. And a great deal more. – Bill Bell Dec 27 '19 at 17:11
  • 1
    I think that is a pretty reasonable way to start. What specifically are you stuck on? Do you have some code you could post? Also +1 @BillBell on sympy: this is a well understood problem with good solutions already available. If you are doing this for a class or for the learning experience though, you may not want to go that route. Again, it sounds like you've already got a good idea on how to start... – Z4-tier Dec 27 '19 at 17:11
  • I don't know how to print it, I now updated my question and added a code @Z4-tier – ArthurMorgan Dec 27 '19 at 17:58
  • Does my answer help? – Sanjit Sarda Dec 28 '19 at 18:41

3 Answers3

1

If you are doing this specifically for a class, or just for the learning, and you want to avoid using sympy in favor of writing your own, then you are off to a good start. Only thing I can suggest is that you might want to print the output in a neater format. Something like this might work:

deriv = ''
poly = ''
for k in range(n):
    poly += str(lista[k]) + "x^" + str(n-k) + " + "
    deriv += str(lista1[k]) + "x^" + str(n-k-1) + " + "
poly += str(lista[-1])
deriv = deriv.rstrip('x^0 +')

print("Input Polynomial: " + poly)
print("Derivative: " + deriv)
Z4-tier
  • 7,287
  • 3
  • 26
  • 42
  • thank you so much, I was doing it for class so using sympy was not really an option :) – ArthurMorgan Dec 27 '19 at 18:55
  • glad to help. That code block I posted is not perfect (doesn't handle zeroes or negative values very well), so you might want to make some changes to handle those corner cases. The formatting and printing is probably harder than the actual problem you're looking to solve :) – Z4-tier Dec 27 '19 at 18:58
0

As you mentioned before, you cant use any modules, because it's for a class, so here is some code that doesn't use modules, although I did not bother to comment, there are some crazy(and in some cases unnecessary) replaces lol.

But anyway here it is:

class Polynomial:

    def __init__(self, input_str):
        self.polynomial_display_string = input_str.replace('**', '^').replace('*', '').replace("x^1+", "x+")\
            .replace("x^1-", "x-").replace('+0', '').replace('-0', '')\
            .replace('+-', '-').replace('-+', '-').replace('--', '+').replace('--', '+')
        self.expression_str = self.polynomial_display_string.replace('^', '**').replace('x', '*x')\
            .replace("x+", "x^1+").replace("x-", "x^1-").replace(' ', '').replace('-+', '-').replace('-', '+-')

    def derivative(self):
        if '+' not in self.expression_str:
            if "x" in self.expression_str:
                constant_multiplier = int(self.expression_str.split('*x**')[0])
                power = int(self.expression_str.split('*x**')[1])
                derivative = (str(constant_multiplier*power) + "*x^" + str(power-1))
                return Polynomial(derivative)
            else:
                return Polynomial('0')
        elif self.expression_str[0] == '+' and not self.expression_str.count('+') > 1:
            constant_multiplier = int(self.expression_str[1:].split('*x**')[0])
            power = int(self.expression_str[1:].split('*x**')[1])
            derivative = (str(constant_multiplier * power) + "*x^" + str(power - 1))
            return Polynomial(derivative)
        else:
            terms = list(filter(None, self.expression_str.split('+')))
            final_str = ""
            for term in terms:
                poly_object = Polynomial(term)
                final_str += "+" + str(poly_object.derivative().expression_str)
            final_str = final_str[1:] if final_str[0] in ['+', '-', ' '] else final_str
            return Polynomial(final_str.replace('++', '+').replace('+-', '-').replace('-+', '-').replace('--', '-')
                              .replace('+', ' + ').replace('-', ' - '))


poly = Polynomial(input('Enter a polynomial'))
print(poly.polynomial_display_string)
print(poly.derivative().polynomial_display_string)
Sanjit Sarda
  • 381
  • 1
  • 4
  • 13
  • This is very complex compared to the solution OP was proposing. It might be helpful if you added some details to explain what benefits this offers that justify the added complexity, and perhaps some details on how to implement it. Why is it a class? Why is it defined recursively? And if it's truly abstracting a polynomial, where are all the other operations one can perform on a polynomial? I can also tell you that it would be much more pythonic to to implement a `__str__` or `__repr__` method instead of this instance level `display_string`. – Z4-tier Dec 29 '19 at 17:14
  • yea ypur ri8 once i got ob it i was like why on earth am i doing this lol – Sanjit Sarda Dec 29 '19 at 17:15
-1

You will need to use a module called sympy. The first thing you need to do is pip install sympy. IF that doesn't work, comment which editor you are using and I might be able to help.

Then you can run this code which explains itself with the help of comments, and which I tested.

import sympy as sp  # Import sympy

x = sp.Symbol('x')  # Makes a new symbol: x

degree = int(input("Degree of Polynomial"))  # get the degree of the polynomial

polynomial = 0  # Start with nothing in the polynomial and slowly add to it

for power in range(degree+1):  # degree + 1 is so that we loop it once more that number of degrees to get x^0 term
    coefficient = int(input(("What is the coefficient of the x^" + str(power) + " term")))
    # Get the coefficient of the term
    if coefficient != 0:  # we do not want to print 0*x^4 or something like that hence only add to the poly if not 0
        polynomial += coefficient*x**power  # coefficient*x^power: Pretty self explanatory

polynomialString = str(polynomial).replace('**', '^')  # Replace pythons symbol for power: ** with ^

print("Your Polynomial is", polynomialString)  # Print the polynomial

derivative = sp.diff(polynomial, x)  # Differentiate the polynomial
derivativeStr = str(derivative).replace('**', '^')  # derivative after replacing ** with ^ 

print("The derivative of ", polynomialString, " is ", derivativeStr)  # Prints the derivative

Sanjit Sarda
  • 381
  • 1
  • 4
  • 13