#
1. 다항식에서 계수의 배열인 px를 가지고 완전한 다항식 형태로 출력하는 함수 printpoly() 선언
2. 변수x의 값을 입력받아서 그 다항식의 값을 구하는 함수 calsPoly() 선언
3. 전역변수 선언(px=[7, -4, 0, 5])
4. 메인코드 부분(출력)
def printpoly(px):
term = len(px)-1
polyStr = "p(x)="
for i in range(len(px)):
coef = px[i]
if (coef >=0):
polyStr+= "+"
polyStr += str(coef) + "x^" + str(term) +" "
term -= 1
return polyStr
def calcPoly(xVal, p_x):
retValue = 0
term = len(p_x) -1
for i in range(len(px)):
coef = px[i]
retValue += coef * xValue ** term
term -=1
return retValue
px= [7, -4, 0, 5]
if __name__ =="__main__":
pStr = printpoly(px)
print(pStr)
xValue= int(input("X값-->"))
pxValue = calcPoly(xvalue, px)
print(pxValue)
#
여기서 if __name__ =="__main__": 이거 왜 쓰는 걸까?
# printPoly() 함수에서 계수가 0인 항은 출력되지 않도록 하고, 첫째항의 +부호도 출력되지 않도록 하기.
def printpoly(px):
term = len(px)-1
polyStr = "p(x)="
for i in range(len(px)):
coef = px[i]
if coef==0:
term-=1
continue
if (coef >0 and term!=len(px)-1):
polyStr+= "+"
polyStr += str(coef) + "x^" + str(term) +" "
term -= 1
return polyStr
px=[7,-4,0,5]
print(printpoly(px))