我能識別序列,但不能識別公式
我有完整的代碼
def analyse_sequence_type(y:list[int]):
if len(y) >= 5:
res = {"linear":[],"quadratic":[],"exponential":[],"cubic":[]}
for i in reversed(range(len(y))):
if i-2>=0 and (y[i] y[i-2] == 2*y[i-1]): res["linear"].append(True)
elif i-3>=0 and (y[i] - 2*y[i-1] y[i-2] == y[i-1] - 2*y[i-2] y[i-3]): res["quadratic"].append(True)
for k, v in res.items():
if v:
if k == "linear" and len(v) 2 == len(y): return k
elif k == "quadratic" and len(v) 3 == len(y): return k
return
print(f"A relation cannot be made with just {len(y)} values.\nPlease enter a minimum of 5 values!")
return
我可以識別linear,quadratic但我該如何做一個函式
uj5u.com熱心網友回復:
因此,首先我們需要為linear和quadratic (下面附上的公式)創建兩個函式。
def linear(y):
"""
Returns equation in format (str)
y = mx c
"""
d = y[1]-y[0] # get difference
c = f"{y[0]-d: }" # get slope
if d == 0: c = y[0] - d # if no difference then intercept is 0
return f"f(x) = {d}x {c} ; f(1) = {y[0]}".replace("0x ","").replace("1x","x").replace(" 0","");
我們對 應用類似的邏輯quadratic:
def quadratic(y):
"""
Returns equation in format (str)
y = ax2 bx c
"""
a = logic_round((y[2] - 2*y[1] y[0])/2) # get a
b = logic_round(y[1] - y[0] - 3*a) # get b
c = logic_round(y[0]-a-b) # get c
return f"f(x) = {a}x2 {b: }x {c: } ; f(1) = {y[0]}".replace('1x2','x2').replace('1x','x').replace(' 0x','').replace(' 0','')
如果您嘗試使用多個輸入的代碼,例如5.0您將得到5.0x 4 (example)。要省略該嘗試:
def logic_round(num):
splitted = str(num).split('.') # split decimal
if len(splitted)>1 and len(set(splitted[-1])) == 1 and splitted[-1].startswith('0'): return int(splitted[0]) # check if it is int.0 or similar
elif len(splitted)>1: return float(num) # else returns float
return int(num)
y只要是域所在的串列,上述函式將以任何方式作業[1, ∞)。
希望這會有所幫助:) 另外,試試立方。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/528401.html
標籤:Python数学序列
上一篇:時間從0到1以HH:MM為單位
