Search code examples
pythonfor-loopvectorization

Vectorize nested loop


given 2 list: solved and country. Need to conjugate each element of country at the end of each of solved ones... and obtain a kinda of matrix frac

I need please suggestion on how speed up the 3 level of loop :

 for i in range(0,len(solved),lung):
            h = solved[i:i+lung]
            for j in range(len(country)):
                g = [h[k]+country[j] for k in range(len(h))]
                frac.append(g)

Solution

  • I solved the issue with very easy code as follows:

    import numpy as np
    
    solved_array = np.array(solved)
    country_array = np.array(country)
        
    # Reshape the arrays for broadcasting
    solved_reshaped = solved_array[:, np.newaxis]
    country_reshaped = country_array[np.newaxis, :]
    frac = np.char.add(solved_reshaped,country_reshaped).tolist() 
    

    this code result over 100+ time faster than previous proposed Enjoy !!