2017-09-08 3 views
0

저는 사용자가 별도의리스트에서 주어진 임의의 다항식의 지수와 지수를 얻기 위해 최선을 다했습니다.별도의리스트에서 다항식의 지수와 지수를 구하십시오.

기본적으로 계수 부분 만 사용되지만 힘 부분은 사용되지 않지만 대신에 변수 목록이 비교 용도로만 사용됩니다. 나는 그것을했지만 작동하지만 코드는 다소 엉성하고 우아하지 않습니다. 이 코드를 작성하는 더 좋은 방법이 있습니까?

무엇 기본적으로해야는 다음과 같습니다

는 사용자의 입력이 말할 때 : 4x3+3이 뭔가를 반환해야합니다 :

coeffs = [4,0,0,3]  

이 내가 호너의 방법을 사용하여 다항식을 해결할 수 있도록합니다.

x = solve(function) 
x.parse() 

: REPL CODE

코드는 다음과 같이 테스트 기능을 실행 :

다음은 실행 가능한 코드입니다.

#!/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 
+0

입력 제한이 있습니까?계수가> = 10 또는 음수가 될 수 있습니까? – konsolas

+0

StackOverflow에 오신 것을 환영합니다. 도움말 설명서의 게시 지침을 읽고 따르십시오. [최소한의 완전하고 검증 가능한 예제] (http://stackoverflow.com/help/mcve)가 여기에 적용됩니다. MCVE 코드를 게시하고 문제를 정확하게 설명하기 전까지는 효과적으로 도움을 드릴 수 없습니다. 게시 된 코드를 텍스트 파일에 붙여넣고 설명한 문제를 재현 할 수 있어야합니다. 특히 주행 프로그램과 운전자가 얻는 결과의 예가 있어야합니다. – Prune

+0

@konsolas 예, 계수는 어떤 숫자보다 클 수 있습니다 – mathmaniage

답변

1

예, 너무 복잡했습니다. 또한 구문 분석에서 오류가 발생했다고 생각합니다. 모든 연산자를 추가 된 것처럼 취급합니다. 공백으로 변경 한 다음 차이점을 무시합니다. 나는 이것을 시험 할 것이지만 당신은 MCVE를 제공하지 못했습니다.

몇 가지 간단한 단계를 제안합니다. 다항식 1 + 4x3-2x를 고려하십시오.

  1. 텍스트에서 하나의 소문자 단일 변수 만 허용한다는 사실을 알고 있습니다. 알파벳 (이미 시스템 패키지에 포함되어 있음)을 정의하는 문제를 겪지 마십시오. 단순히 문자열에서 한 글자를 찾아 구분 기호로 저장하십시오. sep.
  2. 플러스 또는 마이너스 기호로 구분하여 문자열을 스캔하십시오. 기호를으로 유지하십시오. 이렇게하면 목록 ["1", "+4x3", "-2x"]이 생성됩니다.
  3. 목록을 스캔하십시오. sep 변수가없는 문자열의 경우 "x0"을 추가하십시오. sep보다 앞에 숫자가없는 경우 앞에 "1"을 붙이십시오. sep 뒤에 번호가없는 경우 "1"을 추가하십시오. 목록의 첫 번째 요소 일 수있는 "+"앞에 앞에 "+"를 붙입니다. 이제 우리는 ["+1x0", "+4x3", "-2x1"]입니다.
  4. 이제 목록의 각 요소를 검색하십시오. 으로 분할하고으로 변환하고 요소를 정수의 튜플로 변환 [(1, 0), (4, 3), (-2, 1)]
  5. 마지막으로 계수 목록을 작성하십시오. 조건을 호출하십시오. 가장 큰 힘을 얻고 0의 목록의 최대 색인을 작성하십시오. 대응하는 전력의 위치에 대한 계수이다.

코드 :

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

저는 seperator 값으로 x를 알지 못하면 이것을 나눌 수 있다는 사실을 잊어 버렸습니다. 감사! – mathmaniage