mathmaniage
mathmaniage

Reputation: 309

Obtaining powers and coefficients of a polynomial on seperate lists

I've tried my best to obtain the powers and coefficients of an arbitrary polynomial given by user on a seperate list.

Basically, only the coefficient part is used and not the power part, but the list of powers(of variables is used for comparison only). I've done it and it works, but the code is kind of sloppy and non-elegant. Is there a better way to code this?

What is should basically do is:

When the user inputs say: 4x3+3 it should return something like:

coeffs = [4,0,0,3]    

This is so that I can solve the polynomial using Horner's method.

Here's the runnable code: REPL CODE

The code is run with the test function as:

x = solve(function)
x.parse()  

.

    #!/usr/bin/python3


    ######################################################################
    #code information
    #
    #
    #   When the user provides the input of the form
    #   4x3+2x+1
    #   The parse method is expected to return
    #   A coefficient list of the provided polynomial
    #   in ready for use for the horner's method of solving
    #######################################################################




    function = "4x3+2x+1" #this is the sample input the user is expected to give

    #

    class solve:

        def __init__(self, string):
            self.function = string
            self.letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g',
                            'h', 'i', 'j', 'k', 'l', 'm', 'n',
                            'o', 'p', 'q', 'r', 's', 't', 'u',
                            'v', 'w', 'x', 'y', 'z']


        #######################################################################
        #######################################################################
        #######################################################################
        #######################################################################   

        def parse(self):

            signs = ['+', '-', '*']
            for sign in signs:
                self.function = self.function.replace(sign, ' ')#this is where all the
                                                                #signs are converted
                                                                #to spaces





            self.function = self.function.split()       #this is where all the
                                                        #list is split into terms


            self.function.sort(reverse = True)      #the polynomial is sorted always
                                                    #in the decreasing order
                                                    #from higher to lower order of x





            coeffs = []         #list that holds all the coefficients

            powers = []         #list that holds all the powers


            while self.function:
                term = self.function.pop(0)#for each term in the polynomial

                for letter in self.letters: 
                    #check for the alphabets in the letters(The list above)



                    if letter in term:
                        x, y = term.split(letter)
                        coeffs.append(int(x))#append the coefficient to the list
                        if y != '':
                            powers.append(int(y))#append the power to the list
                        else:
                            powers.append(1) #append 1 for x ^ 1 term

                    else:
                        try:
                            temp = int(term) #exception occurs here
                            coeffs.append(temp)#append constant term after exhaution
                                                #of all the polynomial terms
                                                #if no constants exits
                                                #this is not reached
                                                #and neither the line
                                                #directly below
                            powers.append(0)#only for a constant,we have power 0

                            break   #break nonsense to append only once
                        except:
                            pass #exception passed silently


            return self.check_complete(coeffs, powers)








            print("The coefficients are: ", coeffs)
            print("The powers are: ", powers)


            #######################################################################
            #######################################################################
            #######################################################################
            #######################################################################



        def check_complete(self, coeffs, powers):
            """This function checks if the polynomial is a
            complete polynomial that is if it has all the powers of x
            it does this by comparing the two lists hand in hand,
            that is checks the corresponding terms"""

            try:
                #while the function arrives here
                #power and range are assumed to be of same length

                factor = 0  #factor for keeping track of index below

                for index in range(len(powers)):



                    ########################################
                    ########################################
                    Index = index + factor #just cleaning up


                    ########################################
                    ########################################



                    difference = powers[Index] - powers[Index+1]

                    while difference > 1:

                        factor += 1  #factor incremented to keep track
                                     #of where to add
                        difference -= 1

                        coeffs.insert(Index+1, 0)#in the coefficient list
                                            #insert zeros where the
                                            #polynomial is missing a term


            except:

                return coeffs #pass the exception

Upvotes: 0

Views: 732

Answers (1)

Prune
Prune

Reputation: 77850

Yes, you've made this far too complicated. Also, I think you've made an error in the parsing, in that you treat all operators as if they were addition: you change them to spaces and then ignore the differences. I'd test this, but you failed to supply a MCVE.

I suggest some simple steps. Consider the polynomial 1+4x3-2x.

  1. From your text, I gather that you allow only a single variable of a single lower-case letter. Don't go through the trouble of defining an alphabet (which is already in a system package, anyway); simply find the one letter in the string, and store that as the separator, sep.
  2. Scan the string, dividing at any plus or minus sign; keep the sign. This should yield the list ["1", "+4x3", "-2x"].
  3. Scan the list; for any string without the sep variable, append "x0"; for any with no number ahead of sep, prepend a "1"; for any with no number after sep, append a "1"; for any without a leading sign (that can be only the first element of the list", prepend a "+". We now have ["+1x0", "+4x3", "-2x1"].
  4. Now, scan each element of the list. Split at sep and convert the elements to a tuple of integers. [(1, 0), (4, 3), (-2, 1)].
  5. Finally, build your list of coefficients. Let's call the list of tuples terms. Get the highest power and make that the max index of a list of 0's. Then simply assign each coefficient to the location of the corresponding power.

Code:

size = max[z[1] for z in terms] + 1
coeff = [0]*size
for term in terms:
    coeff[term[1]] = term[0]

Upvotes: 1

Related Questions