# python – How do I optimize my code for speed (Codewars.com)

The code passed the initial tests, but failed due to execution timed out. How do I optimize the code (or algorithm) to increase speed?

the question was:

“Consider a sequence u where u is defined as follows:

The number u(0) = 1 is the first one in u.
For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.
There are no other numbers in u.
Example:

u = (1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, …)

1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on…

Given parameter n the function dbl_linear (or dblLinear…) returns the element u(n) of the ordered sequence u (ordered with < so there are no duplicates) .”

and my code:

”’
def dbl_linear(n):

``````u = (1)

if n > 0:

y, z = 2*1+1, 3*1+1

u.append(y), u.append(z)

for i in range(1,n):

y, z = u(i)*2+1, u(i)*3+1

u.append(y), u.append(z)

u = sorted(u)

u = sorted(list(set(u)))

return u(n)
``````

”’

Posted on Categories Articles