다항식 선형 리스트 표현과 계산 프로그램
Q. 계수를 입력하면 다항식 형식에 맞춰 출력하는 함수 printPoly와 x값과 다항식 계수를 입력하면 다항식 계산 값을 출력하는 calc_poly함수를 만들고 [ 7, 4, 0, -5]를 계수로 입력하여 프로그램 출력을 확인해 봅시다.
def printPoly(px):
'''
다항식을 format에 맞게 출력하는 함수
:param px: 계수를 원소로 가지고 있는 리스트
:return: 다항식
'''
term = len(px) - 1 # 최고차항 숫자 = 배열길이-1
poly_str = "P(x) = "
for i in range(len(px)):
coef = px[i] # 계수
if i> 0 and coef > 0:
poly_str = poly_str + "+"
elif coef == 0:
term = term-1
continue
if term == 0:
poly_str = poly_str + f'{coef}'
else:
poly_str = poly_str + f'{coef}x^{term} '
term = term - 1
return poly_str
def calc_poly(xVal, px):
'''
다항식의 산술연산을 하는 함수
:param xVal: int x
:param px: 계수를 원소로 가지고 있는 리스트
:return: 다항식 계산 값
'''
return_value = 0
term = len(px) - 1 # 최고차항 숫자 = 배열길이-1
for i in range(len(px)):
coef = px[i] # 계수
return_value += coef * x_value ** term
term = term - 1
return return_value
## 전역 변수 선언 부분 ##
px = [7, -4, 0, 5] # = 7x^3 -4x^2 +0x^1 +5x^0
## 메인 코드 부분 ##
if __name__ == "__main__":
pStr = printPoly(px)
print(pStr)
x_value = int(input("X값 입력 : "))
px_value = calc_poly(x_value, px)
print(px_value)
Q. 위 코드는 항 차수가 높아지면 반복문의 횟수가 너무 많이 증가하므로 항의 차수를 입력받아 실행하도록 코드를 수정해 봅시다.
def print_poly(tx,px):
'''
다항식을 format에 맞게 출력하는 함수
:param tx : 항 차수를 원소로 가지고 있는 리스트
:param px: 계수를 원소로 가지고 있는 리스트
:return: 다항식
'''
poly_str = "P(x) = "
for i in range(len(px)):
term = tx[i] #항 차수
coef = px[i] # 계수
if i> 0 and coef > 0:
poly_str = poly_str + "+"
elif coef == 0:
continue
if term == 0:
poly_str = poly_str + f'{coef}'
else:
poly_str = poly_str + f'{coef}x^{term} '
return poly_str
def calc_poly(xVal, tx, px):
'''
다항식의 산술연산을 하는 함수
:param xVal: int x
:param tx : 항 차수를 원소로 가지고 있는 리스트
:param px: 계수를 원소로 가지고 있는 리스트
:return: 다항식 계산 값
'''
return_value = 0
for i in range(len(px)):
term = tx[i]
coef = px[i] # 계수
return_value += coef * x_value ** term
return return_value
## 전역 변수 선언 부분 ##
tx = [300,20,0]
px = [7, -4, 5] # = 7x^3 -4x^2 +0x^1 +5x^0
## 메인 코드 부분 ##
if __name__ == "__main__":
pStr = print_poly(tx,px)
print(pStr)
x_value = int(input("X값 입력 : "))
px_value = calc_poly(x_value, tx,px)
print(px_value)
반응형
'Python > 자료구조 알고리즘' 카테고리의 다른 글
| [자료구조 알고리즘] 큐의 일반 구현 (0) | 2023.02.07 |
|---|---|
| [자료구조 알고리즘] 큐 (Queue) (0) | 2023.02.07 |
| [자료구조 알고리즘] 스택 (Stack) (0) | 2023.02.06 |
| [자료구조 알고리즘] 단순 연결 리스트 (0) | 2023.02.06 |
| [자료구조 알고리즘] 선형 리스트 (0) | 2023.02.03 |