我想寫一個函式,只輸入兩個引數:函式的度數為整數,引數為串列,并且能夠對其進行評估。應使用另一種方法評估函式的輸出。
def func(degree: int, params: list) -> Object
pass
In: f = func( 3, [3, 2, -1, 8] )
In:f
Out: 3*x**3 2*x**2 - 1*x 8
In:f(3)
Out: 104
目前,我正在手動操作,高階函式很乏味:
def func(t,a,b,c,d):
return a*pow(t,3) b*pow(t,2) c*t d
uj5u.com熱心網友回復:
SymPyPoly
幾乎擁有您需要的所有電池:
uj5u.com熱心網友回復:
您需要做的就是將系數串列作為……串列發送到您的函式。
def evaluate_polynomial(x : int, a : list):
result = 0
n = len(a)
for i in range(n):
result = a[i] * x**(n-i-1)
return result
assert evaluate_polynomial(3, [3, 2, -1, 8]) == 104
assert evaluate_polynomial(3, [-1, 4, -3, 1, -4, 3, 2, -1, 8]) == 23
uj5u.com熱心網友回復:
一堂課最適合你。它將幫助您定義一個函式,然后使用變數評估該函式。檢查此實作:
class CreateFunction:
def __init__(self, degree: int, weights: list):
self.degree = degree
self.weights = weights
self.powers = [i for i in range(self.degree,-1,-1)]
# making powers of extreme right variables 0
# if the list containing weights has more weights
# than the list containing powers (exponents)
if len(self.weights)>len(self.powers):
difference = len(self.weights) - len(self.powers)
additional_powers = [0 for i in range(difference)]
self.powers = additional_powers
def evaluate(self, variable: int):
sum=0
for (w, p) in zip(self.weights, self.powers):
sum = w*variable**p
return sum
func = CreateFunction(3, [3, 2, -1, 8])
out1 = func.evaluate(3)
print(f'out1={out1}')
out2 = func.evaluate(5)
print(f'out2={out2}')
func2 = CreateFunction(4, [3, 2, -1, 8, 17])
out3 = func2.evaluate(7)
print(f'out3={out3}')
輸出
out1=104
out2=428
out3=7913
uj5u.com熱心網友回復:
一種內置方法。無需將度數作為引數傳遞,它將是系數串列的長度。coefs
是從高到低排列的。
def polynomial(coefs):
return lambda x: sum(c * x**(index-1) for c, index in zip(coefs, range(len(coefs), -1, -1)))
p = polynomial([3, 2, -1, 8])
print(p(3))
#104
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506854.html