Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do I identify sequence equation Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading