how do I identify sequence equation Python

Question:

Am I able to identify sequence, but not formula

I have the whole code

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

I can identify linear and quadratic but how do I make a function

Asked By: WhiteToggled

||

Answers:

So, firstly we will need to create two functions for linear and quadratic (formulae attached below).

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","");

We apply a similar logic for quadratic:

def quadratic(y):
    """
    Returns equation in format (str)
    y = ax² + 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}x² {b:+}x {c:+} ; f(1) = {y[0]}".replace('1x²','x²').replace('1x','x').replace(' +0x','').replace(' +0','')

If you try the code with multiple inputs such as 5.0 you will get 5.0x + 4 (example). To omit that try:

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)

The above functions will work in any way provided that the y is a list where the domain is [1, ∞).

Hope this helps 🙂 Also give cubic a try.

Answered By: The Myth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.