저는 사용자가 별도의리스트에서 주어진 임의의 다항식의 지수와 지수를 얻기 위해 최선을 다했습니다.별도의리스트에서 다항식의 지수와 지수를 구하십시오.
기본적으로 계수 부분 만 사용되지만 힘 부분은 사용되지 않지만 대신에 변수 목록이 비교 용도로만 사용됩니다. 나는 그것을했지만 작동하지만 코드는 다소 엉성하고 우아하지 않습니다. 이 코드를 작성하는 더 좋은 방법이 있습니까?
무엇 기본적으로해야는 다음과 같습니다
는 사용자의 입력이 말할 때 :4x3+3
이 뭔가를 반환해야합니다 :
coeffs = [4,0,0,3]
이 내가 호너의 방법을 사용하여 다항식을 해결할 수 있도록합니다.
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
입력 제한이 있습니까?계수가> = 10 또는 음수가 될 수 있습니까? – konsolas
StackOverflow에 오신 것을 환영합니다. 도움말 설명서의 게시 지침을 읽고 따르십시오. [최소한의 완전하고 검증 가능한 예제] (http://stackoverflow.com/help/mcve)가 여기에 적용됩니다. MCVE 코드를 게시하고 문제를 정확하게 설명하기 전까지는 효과적으로 도움을 드릴 수 없습니다. 게시 된 코드를 텍스트 파일에 붙여넣고 설명한 문제를 재현 할 수 있어야합니다. 특히 주행 프로그램과 운전자가 얻는 결과의 예가 있어야합니다. – Prune
@konsolas 예, 계수는 어떤 숫자보다 클 수 있습니다 – mathmaniage