Search code examples
pythonlistoptimizationtimelist-comprehension

How can i optimize this code? Maybe though a list comporehension?


I need to accelerate this code:

The first which i think i can do is to modify the way to obtain a list, thats the part i write in BOLD.

¿Some ideas? I try to do it with List comprehension but always give me the error of referenced before assignment.

def transform(A, x):
    
    from math import factorial
    
    def comb(i,x):
        return factorial(i)/(factorial(x)*factorial(i-x))

    lis = []

    # --- FROM HERE ---
    for i in A:
        suma = 0
        for j in range(x,i+1):
            suma += comb(j,x)
        lis.append(suma)
    # --- TO HERE ---

    return lis
    
    res = lis[0]  
    
    for i in lis[1:]:
        res = int(res) ^ int(i)
                                        
    return res

Thanks


Solution

  • I'm going to actually answer your specific question, though as mentioned by everyone above, it will almost certainly not improve your running speed. You have:

        suma = 0
        for j in range(x,i+1):
           suma += comb(j,x)
    

    This can be turned into a single sum:

        suma = sum(comb(j, x) for j in range(x, i + 1))
    

    Your outer loop is:

    lis = []
    for i in A:
        suma = sum(....) # See code above
        lis.append(suma)
    

    which can be turned into the following list comprehension:

    lis = [sum(....) for i in A]