Reputation: 1127
How do you optimize this three snippets of code? Especially the third because there are many combinations between the list values and the time is dangerously longer with 1000 inputs.
Code 1:
e00=[]
for i in range(len(c1)):
for j in range(len(d1[i])):
if d1[i][j]%2==0:
d = [c1[i],d1[i][j]]
e00.append(d)
Code 2:
sciezki=[]
for i in range(len(out2)):
x1 = out2[i][-len(out2[i])]
x2 =out2[i][-1]
z1 = nx.shortest_path(g, x1, x2)
if z1 == out2[i] and len(z1)==8:
sciezki.append(z1)
Code 3:
out=[]
for h in range(len(k)):
if len(out)!=0:
k2 = [out, k[h]]
for q in range(len(k2[0])):
for w in range(len(k2[1])):
r = list(chain(k2[0][q],k2[1][w]))
p = [n for n, _ in groupby(r)]
if len(p)==h+2:
out.append(p)
else:
for i in range(len(k[0])):
for j in range(len(k[1])):
r = list(chain(k[0][i],k[1][j]))
p = [n for n, _ in groupby(r)]
if len(p)==3:
out.append(p)
Upvotes: 0
Views: 56
Reputation: 109526
Code 1
Use a conditional list comprehension together with enumeration:
e00 = [[c_val, d_val]
for i, c_val in enumerate(c1)
for d_val d1[i]
if not d_val % 2]
Code 2
Only slight modifications required.
g = ... # Undefined in sample code.
sciezki = []
for out2_val in out2:
x1 = out2_val[-len(out2_val)]
x2 = out2_val[-1]
z1 = nx.shortest_path(g, x1, x2)
if z1 == out2_val and len(z1) == 8:
sciezki.append(z1)
x = '\n'.join(map(str,sciezki)) # Remove if possible.
Upvotes: 1